简体   繁体   中英

Can I extend within a list of lists in python?

I have data that looks like this:

[[1, 100313], [2, 100313], [1, 100314], [3, 100315]]

With everything in string format (otherwise I can't iterate)

I want to run a for loop that looks through these elements and extends with [0, 0, 1] if it sees the second item in the list as 100313. So ultimately it would look like this:

[[1, 100313, 0, 0, 1], [2, 100313, 0, 0, 1], [1, 100314], [3, 100315]]

I've run a for loop that looks like this:

for x, y in list:
    if y == 100313:
        list.extend([0,0,1])

and it doesn't change the list at all. Why is that?

You can do it using list comprehension like this example:

a = [[1, 100313], [2, 100313], [1, 100314], [3, 100315]]

final = [k+[0,0,1] if k[1] == 100313 else k for k in a]

print(final)

Output:

[[1, 100313, 0, 0, 1], [2, 100313, 0, 0, 1], [1, 100314], [3, 100315]]

Update:

You asked to add another if ... else block in one list comprehension . You can do it like this example:

a = [[1, 100313], [2, 100313], [1, 100314], [3, 100315]]
final = [k+[0,0,1] if k[1] == 100313 else k+[0,1,0] if k[1] == 100314 else k for k in a]
print(final)

Output:

[[1, 100313, 0, 0, 1], [2, 100313, 0, 0, 1], [1, 100314, 0, 1, 0], [3, 100315]]

If you deal with big amounts of data and want to avoid inefficient use of memory it's better to use a generator expression. They look pretty similar to list comprehension except for instead of square brackets they have parentheses:

from __future__ import print_function

a = [[1, 100313], [2, 100313], [1, 100314], [3, 100315]]
final = (k+[0,0,1] if k[1] == 100313 else k+[0,1,0] if k[1] == 100314 else k for k in a)

for i in final:
    print(i, end='')

print()

The generator expression returns a generator object instead of a whole list. You can lazily print the elements one by one by looping through the returned generator.

Note that this only makes sense if you have really big lists and not like in the example of your question.

Use list[x][y] instead of y in if statement. And use list[x] instead of list the next line. This will surely work. Because what you are trying to do is you are trying to extend your list, but what you actually want is to extend the element of the list.hope it helps

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