简体   繁体   中英

List comprehension for a list of lists

ok, so I have a list of lists

list = [['a','b','c'], ['1','2','3'], ['x','y','z']]

and I want to edit the first item of each list so it has a symbol before it. A "?" in this example. I figure I can use list comprehension to do this. Something similar to this:

list = ['?'+x for x in i[0] for i in list]

But that just gives me an error. This list comprehension stuff confuses me, how do I do it?

l = [['?' + i[0]] + i[1:] for i in l]    (l is the list you pass in)

First of all, don't name a variable list ; you are now masking the built-in list() type , and can easily lead to bugs if you expect list() to still be that type elsewhere in your code.

To prepend a string to the first element of each nested list, use a simple list comprehension:

outerlist = [['?' + sub[0]] + sub[1:] for sub in outerlist]

This builds a new list from the nested list, by concatenating a one-element list with the first element altered, plus the remainder of the sublist.

Demo:

>>> outerlist = [['a','b','c'], ['1','2','3'], ['x','y','z']]
>>> [['?' + sub[0]] + sub[1:] for sub in outerlist]
[['?a', 'b', 'c'], ['?1', '2', '3'], ['?x', 'y', 'z']]
>>> [['?' + el if i==0 else el for i,el in enumerate(subl)] for subl in L]
[['?a', 'b', 'c'], ['?1', '2', '3'], ['?x', 'y', 'z']]

Also, if you expect to modify initial list, you can modify it inplace without creating a new one:

>>> for sublist in L:
    sublist[0] = '?' + sublist[0]   
>>> L
[['?a', 'b', 'c'], ['?1', '2', '3'], ['?x', 'y', 'z']]

This should work:

>>> l = [['a','b','c'], ['1','2','3'], ['x','y','z']]
>>> [["?"+a,b,c] for [a,b,c] in l]
[['?a', 'b', 'c'], ['?1', '2', '3'], ['?x', 'y', 'z']]
>>> 

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