我想知道是否有一条快捷方式可以在Python列表中列出一个简单的列表.
我可以在for循环中做到这一点,但也许有一些很酷的"单行"?我用reduce尝试了,但是我收到了一个错误.
码
l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
reduce(lambda x, y: x.extend(y), l)
Run Code Online (Sandbox Code Playgroud)
错误信息
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'extend'
Run Code Online (Sandbox Code Playgroud) 因此stdin将文本的一行引回到列表中,并且多行文本都是列表元素.你怎么把它们分成单个单词?
mylist = ['this is a string of text \n', 'this is a different string of text \n', 'and for good measure here is another one \n']
Run Code Online (Sandbox Code Playgroud)
想要输出:
newlist = ['this', 'is', 'a', 'string', 'of', 'text', 'this', 'is', 'a', 'different', 'string', 'of', 'text', 'and', 'for', 'good', 'measure', 'here', 'is', 'another', 'one']
Run Code Online (Sandbox Code Playgroud) 我在下面有一个清单。我想拆分如下:
['动画','儿童','喜剧','冒险','儿童','奇幻','喜剧','浪漫','喜剧','戏剧']
clist = ["Animation|Children's|Comedy",
"Adventure|Children's|Fantasy",
'Comedy|Romance',
'Comedy|Drama']
for i,x in enumerate(clist):
if '|' in x:
clist[i] = x[:x.index('|')]
Run Code Online (Sandbox Code Playgroud)
它返回这个:
['动画'、'冒险'、'喜剧'、'喜剧']
lst = [
"Zambia",
"Zimbabwe",
"Suite,203,2880,Zanker,Rd,San,Jose,95134",
"1496A,1st,and,2nd,Floor,19th,main,8th,crossSector,1,HSR,Layout,Bengaluru,560102",
]
Run Code Online (Sandbox Code Playgroud)
在这里,我有一个世界.有些是实际的话只是一个示例("赞"),有些是喜欢的句子只是例子("组曲,203,2880,Zanker,路,三,圣何塞,95134")
我怎样才能将它们转换成以下格式.
lst = [
"Zambia",
"Zimbabwe",
"Suite",
"203",
"2880",
"Zanker",
"Rd",
"San",
"Jose",
"95134,
"1496A",
"1st",
"and",
"2nd",
"Floor",
"19th",
"main",
"8th",
"crossSector",
"1",
"HSR",
"Layout",
"Bengaluru",
"560102",
"g2crowd_badge2",
"Created with Sketch."
]
Run Code Online (Sandbox Code Playgroud)
如何使用python将列表转换为此格式
请看看这个.