Python 从列表列表中获取字符
我举了一个例子:Python 从列表列表中获取字符,python,list,chars,Python,List,Chars,我举了一个例子: example=[["hello i am adolf","hi my name is "],["this is a test","i like to play"]] 因此,我想得到以下数组: chars2=[['h', 'e', 'l', 'l', 'o', ' ', 'i', ' ', 'a', 'm', ' ', 'a', 'd', 'o', 'l', 'f','h', 'i', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ',
example=[["hello i am adolf","hi my name is "],["this is a test","i like to play"]]
因此,我想得到以下数组:
chars2=[['h', 'e', 'l', 'l', 'o', ' ', 'i', ' ', 'a', 'm', ' ', 'a', 'd', 'o', 'l', 'f','h', 'i', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's'],['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 'i', ' ', 'l', 'i', 'k', 'e', ' ', 't', 'o', ' ', 'p', 'l', 'a', 'y']]
我试过这个:
chars2=[]
for list in example:
for string in list:
chars2.extend(string)
但我得到了以下信息:
['h', 'e', 'l', 'l', 'o', ' ', 'i', ' ', 'a', 'm', ' ', 'a', 'd', 'o', 'l', 'f', 'h', 'i', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 't', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 'i', ' ', 'l', 'i', 'k', 'e', ' ', 't', 'o', ' ', 'p', 'l', 'a', 'y']
尝试使用一个简单的列表
example = [list(item) for sub in example for item in sub]
尝试使用简单的列表理解
example = [list(item) for sub in example for item in sub]
对于每个
列表
,在示例中,您需要在字符2
中添加另一个列表,目前您只是用每个字符直接扩展字符2
范例-
chars2=[]
for list in example:
a = []
chars2.append(a)
for string in list:
a.extend(string)
示例/演示-
>>> example=[["hello i am adolf","hi my name is "],["this is a test","i like to play"]]
>>> chars2=[]
>>> for list in example:
... a = []
... chars2.append(a)
... for string in list:
... a.extend(string)
...
>>> chars2
[['h', 'e', 'l', 'l', 'o', ' ', 'i', ' ', 'a', 'm', ' ', 'a', 'd', 'o', 'l', 'f', 'h', 'i', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' '], ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 'i', ' ', 'l', 'i', 'k', 'e', ' ', 't', 'o', ' ', 'p', 'l', 'a', 'y']]
对于示例中的每个
列表
,您需要在chars2
中添加另一个列表,目前您只是用每个字符直接扩展chars2
范例-
chars2=[]
for list in example:
a = []
chars2.append(a)
for string in list:
a.extend(string)
示例/演示-
>>> example=[["hello i am adolf","hi my name is "],["this is a test","i like to play"]]
>>> chars2=[]
>>> for list in example:
... a = []
... chars2.append(a)
... for string in list:
... a.extend(string)
...
>>> chars2
[['h', 'e', 'l', 'l', 'o', ' ', 'i', ' ', 'a', 'm', ' ', 'a', 'd', 'o', 'l', 'f', 'h', 'i', ' ', 'm', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' '], ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', 'i', ' ', 'l', 'i', 'k', 'e', ' ', 't', 'o', ' ', 'p', 'l', 'a', 'y']]
不提供OP在中提供的内容的仅供参考,我希望获得以下数组:。不提供OP在中提供的内容的仅供参考,我希望获得以下数组:。