python - 如何组合不同列表中的元素
问题描述
我正在尝试使用下面的代码来组合两个列表之间的元素。
输入:
nested_array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
我想要输出:
[[1, 4, 5, 6], [2, 4, 5, 6], [3, 4, 5, 6], [1, 7, 8, 9], ... [6, 7, 8, 9]]
我尝试使用以下内容,但它似乎没有以我想要的格式输出。
你能帮忙吗?
def unique_combination(nested_array):
try:
for n1, array in enumerate(nested_array):
for element in array:
a = [element], list(nested_array[n1+1])
print(a)
except IndexError:
pass
另外,我没有使用 print(),而是尝试使用操作返回。但是对于返回操作,它只返回一个输出。我编码正确吗?
解决方案
在不知道所需的全部输出的情况下,这看起来像是为您提供了您想要的东西。请注意,这可以使用列表推导式写在一行中,但这是令人讨厌的一行。
nested_array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for list_index in range(len(nested_array) - 1):
for marcher_index in range(list_index + 1, len(nested_array)):
for ele in nested_array[list_index]:
print([ele] + nested_array[marcher_index])
输出:
[1, 4, 5, 6]
[2, 4, 5, 6]
[3, 4, 5, 6]
[1, 7, 8, 9]
[2, 7, 8, 9]
[3, 7, 8, 9]
[4, 7, 8, 9]
[5, 7, 8, 9]
[6, 7, 8, 9]
推荐阅读
- qt - C++ QLineEdit 如何限制QLineEdit中输入的数字范围?
- excel - 使用同一行中不同列的结果
- python - 如何使用 apache-beam 读取数据帧
- javascript - 如何在 React.js 的 return 方法中编写 JS 代码
- go - Go 运行时错误:恐慌:运行时错误:无效的内存地址或 nil 指针取消引用
- python - 使用分类嵌入器包时出现问题
- python - 是否可以在端到端测试中使用 Selenium + Webdriver 模拟语音输入?
- git - 提交日历与 PC 时间不同步
- sql - postgresql 连接两个没有关系的表
- reactjs - 由于 eslint 导入/no-webpack-loader-syntax,CRA 无法构建