[英]Taking two lists as input that contain words, to form a tuple with two words, one from each list that have the same starting letter of each word
I've to take two lists as an input which contain words. 我必须将包含单词的两个列表作为输入。 Using those words I form a tuple using two words, one from each list that contain the same first letter of each word.
使用这些单词,我使用两个单词组成一个元组,每个单词列表中的每个单词都包含相同的第一个字母。 Then creating a list of those tuples and printing them.
然后创建这些元组的列表并进行打印。
I have a solution, however, I cannot seem to produce the same item twice. 我有一个解决方案,但是,我似乎无法两次生产相同的产品。 Here's an example of what I mean in words.
这是我用语言表达的一个例子。
List A: ['Jack', 'Tim', 'John', 'Ahmed']
列表A:
['Jack', 'Tim', 'John', 'Ahmed']
List B: ['Julie', 'Tom', 'Henry', 'Harper']
名单B:
['Julie', 'Tom', 'Henry', 'Harper']
c = input().lower()
d = input().lower()
a = c.split()
b = d.split()
x = []
for i in range(len(a)):
if a[i][0] == b[i][0]:
x.append((a[i], b[i]))
print(x)
My Output: [('joy', 'juggle'), ('troy', 'trim')]
我的输出:
[('joy', 'juggle'), ('troy', 'trim')]
Expected Output: [('Jack', 'Julie'), ('John', 'Julie'), ('Tim', 'Tom')]
预期的输出:
[('Jack', 'Julie'), ('John', 'Julie'), ('Tim', 'Tom')]
I'm quite new to learning the language and wasn't quite able to find any similarities to my previous work to find out how I could reiterate through a / b without reproducing the same output. 我对语言学习很陌生,并且无法找到与以前工作相似之处,无法找到如何在不产生相同输出的情况下通过a / b进行重复的工作。
Use itertools.product
to get all the pairs and then filter them out: 使用
itertools.product
获取所有对,然后过滤掉它们:
In [1]: from itertools import product
In [2]: a = ['Jack', 'Tim', 'John', 'Ahmed']
In [3]: b = ['Julie', 'Tom', 'Henry', 'Harper']
In [4]: out = [i for i in product(a, b) if i[0][0] == i[1][0]]
In [5]: out
Out[5]: [('Jack', 'Julie'), ('Tim', 'Tom'), ('John', 'Julie')]
With list comprehensions: 具有列表理解:
In [50]: a = ['Jack', 'Tim', 'John', 'Ahmed']
In [51]: b = ['Julie', 'Tom', 'Henry', 'Harper']
In [55]: c = [(x,y) for x in a for y in b if x.lower()[0]==y.lower()[0]]
In [56]: c
Out[56]: [('Jack', 'Julie'), ('Tim', 'Tom'), ('John', 'Julie')]
你可以试试这个
[(x, y) for x in A for y in B if x[0] == y[0]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.