[英]I want to remove all the numbers in a list less than 80 and move them into another list
This is currently what I have:这是目前我所拥有的:
list = [81,2,78,237,314,50,31]
list0 = []
for i in range(len(list)):
if list [i] < 80:
list0.append(list)
print(list0)
i think i have the setup right, and i just need to know the actual process of moving the numbers我想我的设置是正确的,我只需要知道移动数字的实际过程
I think this is what you're looking for:我认为这就是你要找的:
old = [81,2,78,237,314,50,31]
# Populating the second list:
new = [number for number in list if number < 80]
# Replacing the old list with one matching the criteria:
old = [number for number in list if number >= 80]
print(old, new)
PS: To explicitly remove without creating a new list simply do: PS:要在不创建新列表的情况下显式删除,只需执行以下操作:
for item in new:
old.remove(item)
You should change list0.append(list)
to list0.append(list[i])
.您应该将
list0.append(list)
更改为list0.append(list[i])
。 Your code currently append the entire list
.您的代码当前附加了整个
list
。
I would suggest to not using list
as the variable.我建议不要使用
list
作为变量。 You can use something like original_list
and target_list
, for example.例如,您可以使用
original_list
和target_list
类的东西。
I'm guessing that since you are asked to "move" items to a new list based on a condition, that what you want to do is leverage pop()
this gives you the value you want to move as well as removing it.我猜因为你被要求根据条件将项目“移动”到一个新列表,你想要做的是利用
pop()
这给你你想要移动的值以及删除它。
Since we are also going to be modifying the list we are iterating over by index, we really want to do that backwards from the end so that we don't mess up the indexes of list items we have not visited yet.由于我们还将修改我们正在按索引迭代的列表,因此我们真的希望从末尾向后进行修改,这样我们就不会弄乱我们尚未访问过的列表项的索引。
Putting these thing together you might try:将这些东西放在一起,您可以尝试:
data_1 = [81, 2, 78, 237, 314, 50, 31]
data_2 = []
for i in reversed(range(len(data_1))):
if data_1[i] < 80:
data_2.append(data_1.pop(i))
print(data_1)
print(data_2)
Giving you:给你:
[81, 237, 314]
[31, 50, 78, 2]
or because I love list comprehensions so much, I might do:或者因为我非常喜欢列表理解,我可能会这样做:
data_1 = [81, 2, 78, 237, 314, 50, 31]
data_2 = [
data_1.pop(i)
for i in reversed(range(len(data_1)))
if data_1[i] < 80
]
print(data_1)
print(data_2)
also giving:还给:
[81, 237, 314]
[31, 50, 78, 2]
First, don't use name variable as list
, it is reserved word.首先,不要使用 name 变量作为
list
,它是保留字。
lst = [81,2,78,237,314,50,31]
less_lst = [l for l in lst if l < 80]
gt_lst = [l for l in lst if l >= 80]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.