2016-03-19 17 views
0

は、文字列を組み合わせるとPythonは文字列を組み合わせると

のは、私は2つのリストを持っている、と私は2番目のリストのすべての要素に続く最初のリストの各要素を印刷したいとしましょう、複数回の印刷を複数回印刷します。楽しみのために、 "and"のような2つの要素の間に単語を追加することはできますか?

例:

firstList = (“cats”, “hats”, “rats”) 
secondList = (“dogs”, “frogs”, “logs”) 

私が欲しいもの:私はあなたが何を意味するか理解していれば

cats and dogs 
cats and frogs 
cats and logs 
hats and dogs 
hats and frogs 
hats and logs 
rats and dogs 
etc... 
+0

これを行うにはどうしましたか? [format](https://docs.python.org/2/library/stdtypes.html#str.format)の単純なforループでさえ、良いスタートになります – JGreenwell

答えて

1

次の2つのfor秒でリストの内包表記を使用することができます、1でナンバリングスタートを作るために

>>> words = ["{}: {} and {}".format(i, x, y) for i, (x, y) in enumerate([(x, y) for x in firstList for y in secondList])] 
>>> print(*words) 
0: cats and dogs 
1: cats and frogs 
2: cats and logs 
3: hats and dogs 
4: hats and frogs 
5: hats and logs 
6: rats and dogs 
7: rats and frogs 
8: rats and logs 

:あなたがリストを列挙したい場合は、あなたがこのようenumerateを使用することができ

>>> words = [x + " and " + y for x in firstList for y in secondList] 
>>> print(*words, sep="\n") 
cats and dogs 
cats and frogs 
cats and logs 
hats and dogs 
hats and frogs 
hats and logs 
rats and dogs 
rats and frogs 
rats and logs 

"{}: {} and {}".format(i, x, y)"{}: {} and {}".format(i + 1, x, y)に変更してください。

+0

ありがとうございました!リストに番号を付ける場合はどうすればいいですか? – cparks10

+0

@ cparks10私はその答えを更新しました。 –

1

これは非常に簡単なはずです。

for item1 in firstlist: 
    for item2 in secondlist: 
     print(item1+ " and "+item2) 
1

あなたは、単に値を印刷したい場合は、print声明

ignore = [print('%s and %s' % (a,b)) for b in secondList for a in firstList] 

それともformat

を好む場合を挿入することができ、ネストされたリストの内包

items = ['%s and %s' % (a,b) for b in secondList for a in firstList] 

としてこれを行うことができます

ignore = [print('{0} and {1}'.format(a,b)) for b in secondList for a in firstList] 
1

その他の回答に加えて、これを行う別の方法はitertools.productです。

import itertools 

firstList = (“cats”, “hats”, “rats”) 
secondList = (“dogs”, “frogs”, “logs”) 

for item in itertools.product(firstList, secondList): 
    print(item[0] + " and " + item[1]) 
関連する問題