[英]Splitting lists into to different lists
I have a list:我有一个清单:
list = [['X', 'Y'], 'A', 1, 2, 3]
That I want to split into:我想分成:
new_list = [['X','A', 1, 2, 3] , ['Y', 'A', 1, 2, 3]]
Is this possible?这可能吗?
Sure, take off the first element to create an outer loop, and then loop over the rest of the list to build the sub-lists:当然,去掉第一个元素来创建一个外层循环,然后遍历列表的其余部分来构建子列表:
lst = [['X', 'Y'], 'A', 1, 2, 3]
new_list = []
for item in lst[0]:
sub = [item]
for sub_item in lst[1:]:
sub.append(sub_item)
new_list.append(sub)
Or, as a comprehension:或者,作为一种理解:
new_list = [[item, *lst[1:]] for item in lst[0]]
Where the *lst[1:]
will unpack the slice into the newly created list. *lst[1:]
会将切片解压到新创建的列表中。
Borrowing that idea for the imperative for-loop:借用命令式 for 循环的想法:
new_list = []
for item in lst[0]:
sub = [item, *lst[1:]]
new_list.append(sub)
I'll suggest a more concise approach that uses iterable unpacking -- IMO it's cleaner than using list slices.我将建议一种使用可迭代解包的更简洁的方法——在我看来,它比使用列表切片更简洁。
We take the first element of lst
and separate it from the rest of the list.我们获取
lst
的第一个元素并将其与列表的其余部分分开。 Then, we use a list comprehension to create a new list for every element in the original sublist of lst
:然后,我们使用列表理解为
lst
的原始子列表中的每个元素创建一个新列表:
lst = [['X', 'Y'], 'A', 1, 2, 3]
fst, *rest = lst
[[elem, *rest] for elem in fst]
This outputs:这输出:
[['X', 'A', 1, 2, 3], ['Y', 'A', 1, 2, 3]]
This probably not the best aproach but it works这可能不是最好的方法,但它有效
l = [['X', 'Y'], 'A', 1, 2, 3]
new_list = []
to_append = []
for item in l:
if isinstance(item, list):
new_list.append(item)
continue
to_append.append(item)
new_list.append(to_append)
print(new_list)
Yes, the code below returns exactly what you want.是的,下面的代码返回的正是您想要的。
list = [['X', 'Y'], 'A', 1, 2, 3]
new_list = []
for i, item in enumerate(list[0]):
new_list.append([item] + list[1:])
print(new_list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.