简体   繁体   中英

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:

for item in new:
    old.remove(item)

You should change list0.append(list) to list0.append(list[i]) . Your code currently append the entire list .

I would suggest to not using list as the variable. You can use something like original_list and target_list , for example.

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.

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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM