说我有这个清单
List=[[‘this’ ],[‘is’],[‘a’],[‘sentence’]]
我想拆分内部列表,所以输出看起来像这样
List=[[‘t’,’h’,’i’,’s’],[‘i’,’s’],[‘a’],[‘s’,’e’,’n’,’t’,’e’,’n’,’c’,’e’]]
我试过
print([j for i in list for j in i ])
但输出为[‘this’,’is’,’a’,’sentence ‘]
答案 0 :(得分:1)
您需要进行2项调整:
以下是一个例子:
lst = [['this'],['is'],['a'],['sentence']]
res = [[i for i in sublist[0]] for sublist in lst]
print(res)
[['t', 'h', 'i', 's'],
['i', 's'],
['a'],
['s', 'e', 'n', 't', 'e', 'n', 'c', 'e']]
通过直接向list
提供字符串,可以更简洁地编写内部子列表理解:
res = [list(sublist[0]) for sublist in lst]
答案 1 :(得分:1)
在字符串上调用list
将返回组成字符的字符列表。这可以例如在列表理解中完成:
lst = [['this'], ['is'], ['a'], ['sentence']]
result = [list(x[0]) for x in lst]
答案 2 :(得分:1)
您可以在字符串上调用list()
以获取撰写字符列表:
>> list("anmol")
>> ['a', 'n', 'm', 'o', 'l']
同样,您需要将每个字符串转换为列表:
>> l = [['this' ],['is'],['a'],['sentence']]
>> [list(i[0]) for i in l]
>> [['t', 'h', 'i', 's'], ['i', 's'], ['a'], ['s', 'e', 'n', 't', 'e', 'n', 'c', 'e']]