简体   繁体   中英

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']

List 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')]

Expected Output: [('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.

Use itertools.product to get all the pairs and then filter them out:

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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