Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 拆分并展平字符串列表_Python_List - Fatal编程技术网

Python 拆分并展平字符串列表

Python 拆分并展平字符串列表,python,list,Python,List,这里我有一个单词列表。有些是实际单词,如“赞比亚”,有些是句子,如“Suite,2032880,Zanker,Rd,San,Jose,95134” 如何将它们转换为以下格式 lst = [ "Zambia", "Zimbabwe", "Suite,203,2880,Zanker,Rd,San,Jose,95134", "1496A,1st,and,2nd,Floor,19th,main,8th,crossSec

这里我有一个单词列表。有些是实际单词,如
“赞比亚”
,有些是句子,如
“Suite,2032880,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",
]

您可以使用列表和每个字符串。最后,使用以下方法将结果展平:

尝试:

另一个选项是使用
reduce

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

给定
lst
=您上面的列表

platten_list=[子列表中的子列表中的项目在lst中。拆分(“,”)


来源


这是否回答了您的问题?
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']
res = []    
for i in lst:
   res.extend(i.split(","))   
res = list(reduce(lambda a, b: a + b.split(','), lst, []))