[英]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
; 首先,不要命名变量
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. 你现在正在屏蔽内置的
list()
类型 ,如果你希望list()
仍然是代码中的其他类型 ,那么很容易导致错误。
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']]
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.