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",
]
我在这里有一个世界。有些是实际的单词,例如example(“赞比亚”),有些是句子的示例(“ Suite,203,2880,Zanker,Rd,San,Jose,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."
]
我如何使用python将清单迷恋成这种格式
请看看这个。
答案 0 :(得分:10)
尝试:
res = []
for i in lst:
res.extend(i.split(","))
另一种选择是使用reduce
:
res = list(reduce(lambda a, b: a + b.split(','), lst, []))
答案 1 :(得分:6)
您可以使用列表推导,并split
每个字符串。最后用itertools.chain
将结果展平:
from itertools import chain
list(chain(*[i.split(',') for i in 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']
答案 2 :(得分:3)
给出lst
=您上面的列表
flattened_list = [item for sublist in lst for item in sublist.split(",")]
来源