将嵌套的字符串列表转换为特定顺序的嵌套字符列表python



我有一个列表列表,大致如下:

list_example = [['one', 'two', 'thr'], ['fou','fiv','six']]

目标是将字符串中的每个字符分解成一个新的列表,其中每个列表按每个字符串中的出现顺序排列字符(解释起来很复杂,但像这样(:

new_list = [[['o', 't', 't'], ['n', 'w', 'h'], ['e', 'o', 'r']], [['f','f','s'],['o','i','i'],['u','v','x']]]

我写了一个只适用于一个区块的代码:

list_one = ['one', 'two', 'thr']
broken_up_data = []
for i in range(0, 3):
list_broken_up = [seq[i] for seq in list_one]
broken_up_data.append(list_broken_up)
print(broken_up_data)
>[['o', 't', 't'], ['n', 'w', 'h'], ['e', 'o', 'r']]

但当我试图循环浏览所有列表时,我会得到:

list_example = [['one', 'two', 'thr'], ['fou','fiv','six']]
broken_up_data = []
for x in list_example:
for i in range(0, 3):
list_broken_up = [seq[i] for seq in list_example]
broken_up_data.append(list_broken_up)
print(broken_up_data)
>[['one', 'fou'], ['two', 'fiv'], ['thr', 'six'], ['one', 'fou'], ['two', 'fiv'], ['thr', 'six']]

我可以看到,它正在按字符串在单独字符串中的位置对字符串进行分组(即,"one"one_answers"fou"都排在第一位(,但它不再分解字符串,也没有按照我的意愿正确地循环。这可能是我设置的一个简单的修复方法?

使用zip,可以聚合元素。(获取成对的第一元素、第二元素…(

>>> ['one', 'two', 'thr']
['one', 'two', 'thr']
>>> zip(*['one', 'two', 'thr'])
<zip object at 0x7f68226f4d80>
>>> list(zip(*['one', 'two', 'thr']))
[('o', 't', 't'), ('n', 'w', 'h'), ('e', 'o', 'r')]
# To get lists, not tuples
>>> list(map(list, zip(*['one', 'two', 'thr'])))
[['o', 't', 't'], ['n', 'w', 'h'], ['e', 'o', 'r']]
# or
>>> [list(x) for x in zip(*['one', 'two', 'thr'])]
[['o', 't', 't'], ['n', 'w', 'h'], ['e', 'o', 'r']]

将以上内容应用于给定列表(+列表理解(

>>> list_example = [['one', 'two', 'thr'], ['fou','fiv','six']]
>>> [list(zip(*x)) for x in list_example]
[[('o', 't', 't'), ('n', 'w', 'h'), ('e', 'o', 'r')], [('f', 'f', 's'), ('o', 'i', 'i'), ('u', 'v', 'x')]]
>>> [list(map(list, zip(*x))) for x in list_example]
[[['o', 't', 't'], ['n', 'w', 'h'], ['e', 'o', 'r']], [['f', 'f', 's'], ['o', 'i', 'i'], ['u', 'v', 'x']]]

最新更新