将元素添加到列表中的特定位置
Adding an element to a specific location in a list
#Say I have the lists
l1 = [2,3,6,7,9]
l2 = [11,14,16,20,21]
# and a random number, say 8
x = 8
# And I want to change l1 so that if there is any number larger than
# 8 it will be deleted, then 8 will be inserted into the end of l1
# the output would look like this: [2,3,6,7,8]
# And I want to change l2 so that if there is any number smaller than
# 8 it will be deleted, then 8 will be inserted into the beginning of l2
# the output would look like this: [8,11,14,16,20,21]
我不确定该怎么做,非常感谢您的帮助。谢谢!
使用列表理解:
l1 = [i for i in l1 if i <= 8]
l1 = l1 + [8]
(或l1.append(8)
)
和:
l2 = [i for i in l2 if i >= 8]
l2 = [8] + l2
(或 l2.insert(0, 8)
大概更快)
这是一个解决方案:
l1 = [i for i in l1 if i <= x]
l1.append(x)
l2 = [i for i in l2 if i >= x]
l2.insert(0, x)
#Say I have the lists
l1 = [2,3,6,7,9]
l2 = [11,14,16,20,21]
# and a random number, say 8
x = 8
# And I want to change l1 so that if there is any number larger than
# 8 it will be deleted, then 8 will be inserted into the end of l1
# the output would look like this: [2,3,6,7,8]
# And I want to change l2 so that if there is any number smaller than
# 8 it will be deleted, then 8 will be inserted into the beginning of l2
# the output would look like this: [8,11,14,16,20,21]
我不确定该怎么做,非常感谢您的帮助。谢谢!
使用列表理解:
l1 = [i for i in l1 if i <= 8]
l1 = l1 + [8]
(或l1.append(8)
)
和:
l2 = [i for i in l2 if i >= 8]
l2 = [8] + l2
(或 l2.insert(0, 8)
大概更快)
这是一个解决方案:
l1 = [i for i in l1 if i <= x]
l1.append(x)
l2 = [i for i in l2 if i >= x]
l2.insert(0, x)