繁体   English   中英

使用列表分发列表以删除python中的列表列表

[英]distributing lists with lists to remove lists of lists in python

我有一个清单:

example_list = [x, y, [1, 2, 3], [4,5,6]]

我需要变成两个列表:

j = [x, y, 1, 2, 3]
k = [x, y, 4, 5, 6]

这个示例列表没有规律性,只有当我正在抓取的一页上有两个对象时——比如 contact_page。 一般来说,只有一个联系人,所以列表是:

normal_example_list = [x, y, [1, 2, 3]]

其中“x”来自函数 1,“y”来自函数 2,[1, 2, 3] 来自函数 3 (contact_page),我将它们与 normal_example_list.append() 放在一起

当 contact_page 只有一个列表时,我可以将其展平。 我正在寻找一个规则,它可以遍历列表并删除列表中的第一个列表,然后删除列表中的第二个列表,同时将列表中的所有其他变量保持在它们的位置。

在重新输入我的查询之后思考这个问题

p = []
for i in contact_page:
    p.append(x)
    p.append(y)
    p.append(i)

在我的代码中实现功能会更麻烦,但它可能会起作用。 我希望有一个修复(用文字)

if example_list contains a list:
    new_list1 = [values common to both lists, [first list within list]]
    new_list2 = [values common to both lists, [second list within list]]

从那我可以把它弄平。

看来您想从输入列表中提取所有列表并为每个列表创建一个列表,并结合输入列表中的所有非列表元素。

就像是:

xs = [1, 2, [3, 4, 5], [6, 7, 8], 9, [10]]
singles = [x for x in xs if not isinstance(x, list)]
result = [singles + x for x in xs if isinstance(x, list)]
print(result)

得到你:

[[1, 2, 9, 3, 4, 5], [1, 2, 9, 6, 7, 8], [1, 2, 9, 10]]

暂无
暂无

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

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