简体   繁体   English

从python中的两个列表创建特定对

[英]Create specific pairs from two lists in python

I am currently trying to create specific pairs from two python lists: 我目前正在尝试从两个python列表创建特定对:

Input:
l1 = ["fc1", "fc2"]
l2 = ["fh1", "fh2"]

Expected output:

outl1 = [["fc1","fh1"],["fc2","fh2"]]
outl2 = [["fc2","fh1"],["fc1","fh2"]]

You'll have guessed from this example that a "fc*" must be matched with a "fh*" and that any occurance of the list cannot be repeated in the final output. 您可能从此示例中猜测到,“ fc *”必须与“ fh *”匹配,并且列表的任何出现都不能在最终输出中重复。

I must admit I am quite confused by all the documentation if found online about zip, enumerate, itertools etc... 我必须承认,如果在网上找到有关zip,enumerate,itertools等的所有文档,我会感到非常困惑。

Thanks a lot in advance for your help. 在此先感谢您的帮助。

You can use zip method by passing the both given lists as arguments. 您可以通过传递两个给定列表作为参数来使用zip方法。

For achieving the outl2 list you should use zip method which accepts two arguments : the l1 list, but reversed and l2 list. 为了获得outl2列表,您应该使用zip方法,该方法接受两个argumentsl1列表,但反向列表和l2列表。

zip method makes an iterator that aggregates elements from each of the iterables . zip方法使迭代器 聚合每个可迭代对象中的元素。

With the other words, zip returns an iterator of tuples , where the i-th tuple contains the i-th element from each of the argument sequences or iterables . 换句话说, zip返回一个元组iterator ,其中第i个元组包含每个参数序列或iterables中 的第i个元素。

l1 = ["fc1", "fc2"]
l2 = ["fh1", "fh2"]

print([[a,b] for a,b in zip(l1,l2)])
print([[a,b] for a,b in zip(reversed(l1),l2)])

Output 产量

[['fc1', 'fh1'], ['fc2', 'fh2']]
[['fc2', 'fh1'], ['fc1', 'fh2']]

If I understand you correct, you want to create all possible lists of pairs ('fci', 'fhj'), such that in each list all the 'fci' appear only once and the same for 'fhj'. 如果我理解正确的话,您想创建所有可能的配对列表(“ fci”,“ fhj”),以便在每个列表中所有“ fci”仅出现一次,而对于“ fhj”则相同。

You can use itertools.permuations to achieve this. 您可以使用itertools.permuations来实现。 I generalized your example to include 3 elements per list. 我将您的示例概括为每个列表包含3个元素。

from itertools import permutations 

A = ["fc1", "fc2", "fc3"]
B = ["fh1", "fh2", "fh3"]

B_permuations = permutations(B)

for perm in B_permuations:
    print([[a, b] for a, b in zip(A, perm)])

This will give you ​ 这会给你

[['fc1', 'fh1'], ['fc2', 'fh2'], ['fc3', 'fh3']]
[['fc1', 'fh1'], ['fc2', 'fh3'], ['fc3', 'fh2']]
[['fc1', 'fh2'], ['fc2', 'fh1'], ['fc3', 'fh3']]
[['fc1', 'fh2'], ['fc2', 'fh3'], ['fc3', 'fh1']]
[['fc1', 'fh3'], ['fc2', 'fh1'], ['fc3', 'fh2']]
[['fc1', 'fh3'], ['fc2', 'fh2'], ['fc3', 'fh1']]

if enumerate , zip and such is overwhelming at first use a simple for loops 如果enumeratezip等一开始enumerate ,请使用简单的for循环

l1 = ["fc1", "fc2"]
l2 = ["fh1", "fh2"]

a = []
for i1 in l1:
    a.append([[i1,i2] for i2 in l2])

for i in a:
    print(i)

output 产量

[['fc1', 'fh1'], ['fc1', 'fh2']]
[['fc2', 'fh1'], ['fc2', 'fh2']]

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

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