gpt4 book ai didi

python - 将元素添加到列表中的特定位置

转载 作者:行者123 更新时间:2023-11-28 21:48:26 24 4
gpt4 key购买 nike

#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) 可能更快)

关于python - 将元素添加到列表中的特定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35371426/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com