📜  Python|将给定元素移动到列表开始

📅  最后修改于: 2022-05-13 01:55:00.099000             🧑  作者: Mango

Python|将给定元素移动到列表开始

涉及元素移位的传统问题已在前面多次讨论过,但有时我们在执行它们时有严格的限制,并且了解任何可能的变化都会有所帮助。本文讨论了在列表开头移动 K 的一个这样的问题,这里要注意的是它只检查 K,不包括常规的“无”(False)值。让我们讨论可以执行此操作的某些方式。

方法 #1:使用列表理解 + isinstance()
在该方法中,我们分两步执行移位操作。在第一步中,我们获得了我们需要在前面获得的所有值,最后我们只是将 K 推到前面。 isinstance 方法用于过滤出 Boolean False 实体。

# Python3 code to demonstrate 
# Move all K element to List Start
# using list comprehension + isinstance() 
  
# initializing list 
test_list = [1, 4, None, "Manjeet", False, 4, False, 4, "Nikhil"] 
  
# printing original list 
print("The original list : " + str(test_list)) 
  
# initializing K 
K = 4
  
# using list comprehension + isinstance() 
# Move all K element to List Start
temp = [ele for ele in test_list if ele != K and ele or ele is None or isinstance(ele, bool) ] 
res = [K] * (len(test_list) - len(temp)) + temp
  
# print result 
print("The list after shifting K's to start : " + str(res)) 
输出 :
The original list : [1, 4, None, 'Manjeet', False, 4, False, 4, 'Nikhil']
The list after shifting K's to start : [4, 4, 4, 1, None, 'Manjeet', False, False, 'Nikhil']

方法 #2:使用列表理解 + isinstance() + 列表切片
此方法与上述方法类似,唯一的修改是为了减少步骤数,使用列表切片来附加 K 以仅 1 步执行整个任务。

# Python3 code to demonstrate 
# Move all K element to List Start
# using list comprehension + isinstance() + list slicing 
  
# initializing list 
test_list = [1, 4, None, "Manjeet", False, 4, False, 4, "Nikhil"] 
  
# printing original list 
print("The original list : " + str(test_list)) 
  
# initializing K 
K = 4
  
# using list comprehension + isinstance() + list slicing 
# Move all K element to List Start
res = ([K] * len(test_list) + [ele for ele in test_list if ele != K and ele or not isinstance(ele, int) 
    or isinstance(ele, bool)])[len([ele for ele in test_list if ele != K and ele or not isinstance(ele, int) 
    or isinstance(ele, bool)]):] 
  
# print result 
print("The list after shifting K's to end : " + str(res)) 
输出 :
The original list : [1, 4, None, 'Manjeet', False, 4, False, 4, 'Nikhil']
The list after shifting K's to start : [4, 4, 4, 1, None, 'Manjeet', False, False, 'Nikhil']