python - 将列表中的元素与列表列表中的每个元素进行比较

标签 python python-2.7 python-itertools

我正在尝试将一个列表中的元素与列表列表中的每个元素进行比较。

hsdr_machine_one=['P#1', 'P#2', ...]
hsdr_machine_two=[...]
hsdr_machine_three=[...]

hsff_machine_four=['P#4', 'P#5', ...]
hsff_machine_five=['P#6', ...]
hsff_machine_six=[...]

hsdr_machines_list=[hsdr_machine_one, hsdr_machine_two, hsdr_machine_three]
hsff_machines_list=[hsff_machine_four, hsff_machine_five, hsff_machine_six]

part_number_combinations = []
for part_number in itertools.product(*hsdr_machines_list):
    part_number_combinations = [part_number[0]] + [part_number[1]]
    print part_number_combinations

我知道这段代码不会让我到达那里,这只是我在 itertools 中搞乱的东西。 。我正在使用 product(hsdr_machine_one, hsff_machine_four)早些时候,仅比较两台机器就取得了成功。但现在我想尝试一次完成这一切。

输出为:

P#1, P#4
P#1, P#5
P#1, P#6
P#2, P#4
P#2, P#5 ...

然后它将继续比较 hsdr_machine_twohsff_machine_four , five ,和six .

最佳答案

您可以使用itertools.products创建子列表的组合,然后一次使用两个子列表中的项目获取对的乘积:

for hsdr, hsff in itertools.product(hsdr_machines_list, hsff_machines_list):
    for pt1, pt2 in itertools.product(hsdr, hsff):
         print pt1, pt2

关于python - 将列表中的元素与列表列表中的每个元素进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45199903/

相关文章:

python - 使用 openpyxl 插入表格

Python:查找与列表字典中的项目相对应的键

python - itertools.repeat VS itertools.cycle

python - itertools.imap vs 映射整个可迭代对象

python - Tkinter 窗口中 cv2 图像上的鼠标事件

python - 检查多个模拟的调用顺序

python - 如何通过IF语句简化变量赋值

python - 如何将 stdout 重定向到 Tkinter Text 小部件

python - Spark - 为我的 Spark 作业分配了多少执行器和内核

python - OpenCV 中的 Matlab 函数 (improfile) - Python 2.7