展平字符串列表的列表 [英] Flatten list of list of strings
问题描述
我有这个列表:
list1 = ["['word']", "['second', 'first']", "['first']"]
随着项目被转换为字符串,您会发现它并不完全是字符串列表.
You can see it's not exactly a list of list of strings as the items were converted into strings.
我想要这个拼合的输出:
I want to have this flattened output:
list2 = ['word', 'second', 'first', 'first']
只是一个简单的字符串列表.
Just a simple list of strings.
我尝试过使用这种方式:
I 've tried using this way:
list2 = [ x.strip('[]') for x in list1]
但是问题在于第二项仍被视为一项:
But the issue is with the second item still considered as one item:
["'word'", "'second', 'first'", "'first'"]
所以我尝试用逗号分割:
So I tried splitting by comma:
list3 = [item.split(',') for x in list2 for item in x]
但是它给出了以下输出:
But it gave this output:
[["'"],
['w'],
['o'],
['r'],
['d'],
["'"],
["'"],
['s'],
['e'],
['c'],
['o'],
['n'],
['d'],
["'"],
['', ''],
[' '],
["'"],
['f'],
['i'],
['r'],
['s'],
['t'],
["'"],
["'"],
['f'],
['i'],
['r'],
['s'],
['t'],
["'"]]
有什么办法解决这个问题吗?
Any idea how to fix this?
在@AKX的帮助下
list2 = [ast.literal_eval(item) for item in list1]
然后使用此功能:
def flatten(lst):
for el in lst:
if isinstance(el, list):
yield from el
else:
yield el
list3 = flatten(list2)
list(list3)
这给出了:
['word', 'second', 'first', 'first']
更新2
@waynelpu提供的一种优化的替代解决方案,而不是 flatten 函数,只需使用:
list2 = [inner for item in list1 for inner in ast.literal_eval(item)]
推荐答案
如果您有一个表示列表的Python表达式字符串列表(嵌套子句的表达式如何),则必须使用 ast.literal_eval()
回到现实.
If you have a list of strings of Python expressions that represent lists (how's that for a nested clause), you will have to use ast.literal_eval()
to get back to reality, as it were.
>>> import ast
>>> list1 = ["['word']", "['second', 'first']", "['first']"]
>>> list2 = [ast.literal_eval(item) for item in list1]
[['word'], ['second', 'first'], ['first']]
使用 ast.literal_eval()
,而不是您不应该使用的危险 eval()
是安全的,因为它只计算没有副作用的文字.
Using ast.literal_eval()
, as opposed to the dangerous eval()
that you shouldn't use is safe, as it only evaluates literals that can have no side effects.
这篇关于展平字符串列表的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!