简体   繁体   English

拆分和展平字符串列表

[英]Split and flatten a list of strings

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",
]

Here I have a list of words.在这里,我有一个单词列表。 Some are actual words like "Zambia" and some are sentences like "Suite,203,2880,Zanker,Rd,San,Jose,95134" .有些是像"Zambia"这样的实际单词,有些是像"Suite,203,2880,Zanker,Rd,San,Jose,95134"这样的句子。

How can I convert them into the below format?如何将它们转换为以下格式?

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."
]

try:尝试:

res = []    
for i in lst:
   res.extend(i.split(","))   

Another option is to use reduce :另一种选择是使用reduce

res = list(reduce(lambda a, b: a + b.split(','), lst, []))

You can use a list comprehension andsplit each string.您可以使用列表理解并split每个字符串。 Finally flatten the result with itertools.chain :最后用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']

Given lst = your list above鉴于lst = 你上面的列表

flattened_list = [item for sublist in lst for item in sublist.split(",")]


Sources来源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM