[英]how to convert element at index 1 to upper() in a nested list?
How can I convert each element at index 1 in the inner list to upper() using only list comprehension. 如何仅使用列表理解将内部列表中索引1处的每个元素转换为upper()。
ed_sheeran = [ [j.upper() for j[1] in i ] for i in ed_sheeran ] # My code but not working.
ed_sheeran = [[' ', 'w', 'h', 'i', 't', 'e', ' ', 'l', 'i', 'p', 's', ',', ' ', 'p', 'a', 'l', 'e', ' ', 'f', 'a', 'c', 'e', ' '], [' ', 'b', 'r', 'e', 'a', 't', 'h', 'i', 'n', 'g', ' ', 'i', 'n', ' ', 's', 'n', 'o', 'w', 'f', 'l', 'a', 'k', 'e', 's', ' '], [' ', 'b', 'u', 'r', 'n', 't', ' ', 'l', 'u', 'n', 'g', 's', ' ', 's', 'o', 'u', 'r', ' ', 't', 'a', 's', 't', 'e', ' ']]
for i in ed_sheeran:
i[1] = i[1].upper()
print(ed_sheeran)
Output:
[[' ', 'W', 'h', 'i', 't', 'e', ' ', 'l', 'i', 'p', 's', ',', ' ', 'p', 'a', 'l', 'e', ' ', 'f', 'a', 'c', 'e', ' '], [' ', 'B', 'r', 'e', 'a', 't', 'h', 'i', 'n', 'g', ' ', 'i', 'n', ' ', 's', 'n', 'o', 'w', 'f', 'l', 'a', 'k', 'e', 's', ' '], [' ', 'B', 'u', 'r', 'n', 't', ' ', 'l', 'u', 'n', 'g', 's', ' ', 's', 'o', 'u', 'r', ' ', 't', 'a', 's', 't', 'e', ' ']]
只需将列表的其他部分缝合在一起,确保所有元素都在列表中。
[[x[0], x[1].upper()] + x[2:] for x in ed_sheeran]
只是枚举子列表,如果索引值为1,则将单个元素更改为上
[[y.upper() if i==1 else y for i,y in enumerate(x)] for x in ed_sheeran]
.upper()
will return a new string, not update it inplace - and, on the other hand, the attribution statement =
is not meant to be used inside expressions such as list comprehensions. .upper()
将返回一个新字符串,而不是就地更新它;另一方面,属性声明=
不能在列表理解之类的表达式中使用。
Replacing a list element is possible in an expression, though, if one call the __setitem__
method on the list, which is ordinarily done by the =
. 但是,如果一个表达式调用列表上的
__setitem__
方法(通常由=
完成),则可以在表达式中替换列表元素。 If one wants to "look clean" by not calling the dunder __setitem__
methos directly, it is possible to use operator.setitem
to do that as an expression: 如果不想通过直接调用dset
__setitem__
方法来“看上去干净”,则可以使用operator.setitem
作为表达式来实现:
from operator import setitem
ed_sheeran = [setitem(part, 1, part[1].upper()) for part in ed_sheeran ]
Or, if you prefer without importing setitem
: 或者,如果您愿意不导入
setitem
:
ed_sheeran = [part.__setitem__(1, part[1].upper()) for part in ed_sheeran]
Actually, this is done inplace, so you don't even need to re-assign the outter-list - although if you don't want to create a new-list in memory, and use a generator expression you will need to "consume" the generator. 实际上,这是就地完成的,因此您甚至不需要重新分配外列表-尽管如果您不想在内存中创建新列表并使用生成器表达式,则需要“消耗”发电机。 The "any" built-in is a nice one in this case:
在这种情况下,内置的“ any”是一个不错的选择:
any(part.__setitem__(1, part[1].upper()) for part in ed_sheeran)
(this works only because __setitem__
returns None) (这仅因为
__setitem__
返回None才有效)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.