Python列表和for循环

时间:2015-01-26 17:37:40

标签: python-2.7 for-loop

我希望这段代码可以打印spade:a spade:2依旧直到heart:K。
但它只有心:A to heart:K。
我该怎么办?

symbols = ["spade", "clover", "diamond", "heart"]
numbers = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q",       "K"]
cards = {}

for num in numbers:
    for symbol in symbols:
        cards[num] = symbol

print cards

3 个答案:

答案 0 :(得分:1)

问题是你没有以正确的方式进行迭代,因此你没有附加在列表中。正确的方法是

symbols = ["spade", "clover", "diamond", "heart"]
numbers = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q",         "K"]
cards = []

for j in range(len(symbols)):
    for i in range(len(numbers)):
       cards.append(str(symbols[j]+':'+str(numbers[i])))

print cards

带输出:

['spade:A', 'spade:2', 'spade:3', 'spade:4', 'spade:5', 'spade:6', 'spade:7',  'spade:8', 
'spade:9', 'spade:10', 'spade:J', 'spade:Q', 'spade:K', 'clover:A', 'clover:2',
'clover:3', 'clover:4', 'clover:5', 'clover:6', 'clover:7', 'clover:8', 'clover:9',
'clover:10', 'clover:J', 'clover:Q', 'clover:K', 'diamond:A', 'diamond:2', 'diamond:3',
'diamond:4', 'diamond:5', 'diamond:6', 'diamond:7', 'diamond:8', 'diamond:9', 'diamond:10',
'diamond:J', 'diamond:Q', 'diamond:K', 'heart:A', 'heart:2', 'heart:3', 'heart:4',
'heart:5', 'heart:6', 'heart:7', 'heart:8', 'heart:9', 'heart:10', 'heart:J', 'heart:Q', 'heart:K']

在python 2.7中用Ipython Notebook制作

希望它有所帮助。

答案 1 :(得分:1)

使用您的itertools工具箱

import itertools

symbols = ["spade", "clover", "diamond", "heart"]
numbers = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q",       "K"]

combinations = itertools.product(symbols, numbers)

cards = ["{}:{}".format(suit, rank) for suit,rank in combinations]

这会给你列表:

['spade:A',
 'spade:2',
 'spade:3',
 'spade:4',
 'spade:5',
 'spade:6',
 'spade:7',
 'spade:8',
 'spade:9',
 'spade:10',
 'spade:J',
 'spade:Q',
 'spade:K',
 'clover:A',
 'clover:2',
 'clover:3',
 'clover:4',
 'clover:5',
 'clover:6',
 'clover:7',
 'clover:8',
 'clover:9',
 'clover:10',
 'clover:J',
 'clover:Q',
 'clover:K',
 'diamond:A',
 'diamond:2',
 'diamond:3',
 'diamond:4',
 'diamond:5',
 'diamond:6',
 'diamond:7',
 'diamond:8',
 'diamond:9',
 'diamond:10',
 'diamond:J',
 'diamond:Q',
 'diamond:K',
 'heart:A',
 'heart:2',
 'heart:3',
 'heart:4',
 'heart:5',
 'heart:6',
 'heart:7',
 'heart:8',
 'heart:9',
 'heart:10',
 'heart:J',
 'heart:Q',
 'heart:K']

答案 2 :(得分:0)

你正在迭代这些符号,但是当你在第二个循环中查看数字时,实际上你正在替换前一个循环设置的值,因此你只剩下最后一个循环中的值并且所有内容都被替换。这意味着卡片[“A”]值在循环中设置4次,“心脏”的最后一个值保留。所有其他索引都会发生同样的事情。