简体   繁体   English

将嵌套列表拆分为不同的列表

[英]Split nested lists into different lists

I have a list like this:我有一个这样的列表:

list1=[['xx', 'xx', 'xx', 'xx', 'xx'],
 ['yy', 'yy', 'yy', 'yy', 'yy'],
 ['zz',
  'zz',
  'zz',
  'zz',
  'zz',
  'zz',
  'zz',
  'zz',
  'zz'],
 ['tt', 'tt', 'tt', 'tt', 'tt']
.
.
.
n]

I would like to have a method to cast the nested lists into different lists.我想要一种将嵌套列表转换为不同列表的方法。 However, as the length of list1 differs every time my program executes I want to have an automated procedure但是,由于每次我的程序执行时list1的长度都不同,我想要一个自动化的过程

For example, the expected outcome looks like that.例如,预期的结果是这样的。

list1= ['xx', 'xx', 'xx', 'xx', 'xx']
list2= ['yy', 'yy', 'yy', 'yy', 'yy', 'yy']
list3= ['zz', 'zz', 'zz', 'zz', 'zz', 'zz', 'zz', 'zz', 'zz']
list4= ['tt', 'tt', 'tt', 'tt', 'tt']
.
.
.
listn=[...........]

Any ideas?有任何想法吗?

This is not a good practice at all Use list[index] to get the list at any position, Like use list[45] to get the list at index 45.这根本不是一个好习惯使用 list[index] 在任何 position 处获取列表,就像使用 list[45] 在索引 45 处获取列表一样。

but if you want then you can use this code.但如果你愿意,你可以使用这个代码。

Try this尝试这个

full_list=[['xx', 'xx', 'xx', 'xx', 'xx'],
 ['yy', 'yy', 'yy', 'yy', 'yy'],
 ['zz',
  'zz',
  'zz',
  'zz',
  'zz',
  'zz',
  'zz',
  'zz',
  'zz'],
 ['tt', 'tt', 'tt', 'tt', 'tt']]

allListName = []
for i in range(1,len(full_list)+1):
    exec(f"list{i}={full_list[i-1]}")
    allListName.append(f'list{i}')
print(allListName)
print(list1)
print(list2)
# print(listn)

OUTPUT OUTPUT

['list0', 'list1', 'list2', 'list3']
['yy', 'yy', 'yy', 'yy', 'yy']
['zz', 'zz', 'zz', 'zz', 'zz', 'zz', 'zz', 'zz', 'zz']

  1. In the loop i is the index of the list in the full_list and the list[i] is the list at the i index.在循环中, ifull_list中列表的索引,而list[i]i索引处的列表。

  2. exec function run string as a code block so the in this case string is f'list{i}={list[i]}' so this string is executed as a string. exec function 将字符串作为代码块运行,因此在这种情况下,字符串为f'list{i}={list[i]}' ,因此该字符串作为字符串执行。

  3. if i is 1 then list1=['xx', 'xx', 'xx', 'xx', 'xx'] and soon.如果 i 是 1,那么list1=['xx', 'xx', 'xx', 'xx', 'xx']很快。

  4. For the allListName this contains all the nested list names that are created in the loop.对于allListName ,它包含在循环中创建的所有嵌套列表名称。

  5. If you want all nested names with the value to print then use this code below the loop.如果您希望打印所有具有该值的嵌套名称,请在循环下方使用此代码。

for an in allListName:
    print(f'{a} = {locals()[a]}')

Output Output

list1 = ['xx', 'xx', 'xx', 'xx', 'xx']
list2 = ['yy', 'yy', 'yy', 'yy', 'yy']
list3 = ['zz', 'zz', 'zz', 'zz', 'zz', 'zz', 'zz', 'zz', 'zz']
list4 = ['tt', 'tt', 'tt', 'tt', 'tt']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM