简体   繁体   English

将两个列表与嵌套的for循环串联在一起

[英]Concatenate two lists with nested for loops in Python

I want to create a list of string elements that is a deck of cards. 我想创建一串纸牌的字符串元素。

I created two lists of strings (1-Ace and suites). 我创建了两个字符串列表(1-Ace和suites)。 I want to use nested for loops to do this, and include a word in-between the two (" of "). 我想使用嵌套的for循环来做到这一点,并在两者之间添加一个单词(“ of”)。 I did this quickly and easily when printing everything, but when I went to append to another list (deck) I've run into problems creating the string variable that I want. 在打印所有内容时,我可以快速轻松地做到这一点,但是当我追加到另一个列表(卡片组)时,遇到了创建所需的字符串变量的问题。

EDIT: I'm receiving the following error: "inconsistent use of tabs and indentation". 编辑:我收到以下错误:“选项卡和缩进的使用不一致”。
I'm currently using notepad++, but I'd gotten the same error earlier when I was using the IDLE. 我当前使用的是notepad ++,但是使用IDLE时,我遇到了同样的错误。

nums = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"]
suite = ["Diamonds", "Hearts", "Clubs", "Spades"]
deck = []

for element in nums:
    for suit in suite:
        card = "%s of %s" % (element, suit)
        deck.append(card)
        print (deck)

My goal is to have a list of strings similar to this ... ["1 of hearts", "Ace of spades"]... 我的目标是要有一个与此类似的字符串列表... [“ 1心”,“黑桃A”] ...

Thanks! 谢谢!

The error points to improper mixing of tabs and spaces. 该错误表明制表符和空格的混合不正确。 Most text editors offer an option 'replace tabs by spaces' or something similar. 大多数文本编辑器都提供“用空格替换制表符”或类似选项。 Or, if you plan to stick with Python, I strongly recommend using a serious IDE like PyCharm (my favourite) or Eclipse/PyDev . 或者,如果您打算使用Python,我强烈建议您使用严肃的IDE,例如PyCharm (我的最爱)或Eclipse / PyDev

Other than that, there is nothing wrong with the code you posted. 除此之外,您发布的代码没有任何问题。 itertools.product is your friend if you want to ease the task though (and avoid indentation altogether): 如果您想简化任务(并且完全避免缩进),则itertools.product是您的朋友:

from itertools import product

deck = [' of '.join(p) for p in product(nums, suite)]

Or even shorter with the help of map : 甚至在map的帮助下更短:

deck = map(' of '.join, product(nums, suite))

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

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