简体   繁体   English

我的python列表理解由于语法错误而失败

[英]My python list comprehension fails due to a syntax error

Python noob using version 3.2.3... 使用3.2.3版的Python noob ...

class Card:
    def __init__(self, suitID, rank):
            self.suits = ("Spades", "Hearts", "Diamonds","Clubs")
            self.rank = rank
            self.suit = self.suits[suitID]

    def __str__(self):
            return (str("%s of %s" % (self.rank, self.suit)))


class Deck:
    def __init__(self):
            self.cards = [Card(i//13, i%13) for i in range(52)]

The above is how I have things set up, seems fine to me. 以上是我的设置方法,对我来说似乎不错。 The confusion is in the following (please ignore the return ("") statement as this is only for testing) 以下是混淆(请忽略return(“”)语句,因为这仅用于测试)

Case 1: 情况1:

def __str__(self):
    print ( self.cards [i for i in range (52) ] )
    return("")

Output: 输出:

File "cardgame.py", line 21
print (self.cards[i for i in range(52)])
                      ^
SyntaxError: invalid syntax

Why the error? 为什么会出错? I thought that was how LC's were used... 我以为那是LC的使用方式...


Case 2: 情况2:

def __str__(self):
    print (myCards for myCards in self.cards)
return ("")

Output: 输出:

<generator object <genexpr> at 0x2256fa0>

Again, what does that mean, and why does it not output the data? 同样,这是什么意思,为什么它不输出数据?


Case 3: 情况3:

def __str__(self):
    for myCard in self.cards:
          print (myCard)
    return ("")

Output: 输出:

0 of Spades
1 of Spades
2 of Spades
3 of Spades
4 of Spades
...
..
.

Now this outputs exactly what I want, but that confuses me ever more. 现在,这恰好输出了我想要的东西,但这使我更加困惑。 I was under the impression that all three cases are equivalent and they are clearly not. 我的印象是,这三种情况都是等效的,而显然不是。 What are the differences? 有什么区别?

Thanks in advance. 提前致谢。

Case 1: 情况1:

You should pass an integer rather than i for i in range (52) as the index of a list. 您应该将整数(而不是i for i in range (52)传递i for i in range (52)中的i for i in range (52)作为列表的索引。 Try print [self.cards[i] for i in range(52)] . 尝试print [self.cards[i] for i in range(52)] And you can just write print self.cards if there are only 52 cards in self.cards . 如果print self.cards中只有52张卡,则可以写出print self.cards self.cards

Case 2 & Case 3: 情况2和情况3:

(myCards for myCards in self.cards) is a generator in Python. (myCards for myCards in self.cards)是Python中的生成器 You can iterate it like a list in Case 3, but it will not return all its elements at first, which is an important feature of generators. 您可以像案例3中的列表一样对其进行迭代,但是一开始它不会返回其所有元素,这是生成器的重要功能。

The is is List Comprehensions, you'd better to learn it's gramar. 是列表理解,您最好学习它的语法。

li = [1,2,3] li = [1,2,3]

la = [i for i in li] # the la is a list [1,2,3] la = [i for i in li]#la是一个列表[1,2,3]

lb = (i for i in li) # lb is a generator object, and list(lb) is [1,2,3] lb =(i对i in li)#lb是一个生成器对象,list(lb)是[1,2,3]

in case 1, print [self.cars[i] for i in range(52)] will work. 在情况1中,可以print [self.cars[i] for i in range(52)]

in your code (self.cars[i for i in range(52)]) , the [i for i in range(52)] is a list,so self.cars[list objeject] is invalid. 在您的代码(self.cars[i for i in range(52)])[i for i in range(52)] (self.cars[i for i in range(52)])[i for i in range(52)]是一个列表,因此self.cars[list objeject]无效。

print (self.cards[i for i in range(52)])

You are trying to use a list to index into a list. 您正在尝试使用列表索引到列表中。 This is like doing the following: 就像执行以下操作:

>>> l = [4,5,6]
>>> l[i for i in range (3)]
  File "<stdin>", line 1
    l[i for i in range (3)]

For your first case, that is not how you arrange Python syntax. 对于第一种情况,这不是安排Python语法的方式。

print(self.cards[i for i in range (52)])

You are indexing a list with another list . 你是一个索引list与另一个list It doesn't make any sense. 这没有任何意义。 What you probably meant to do was this: 您可能打算做的是:

print([self.cards[i] for i in range(52)])

Note that this just creates a new list . 请注意,这只是创建一个新list The expression [self.cards[i] for i in range(52)] , operating on a list with 52 elements, has the same result as self.cards . 在具有52个元素的list上运行的表达式[self.cards[i] for i in range(52)]具有与self.cards相同的结果。 You are adding unnecessary stuff and going in circles. 您正在添加不必要的内容并转圈。

For your second case, this: 对于第二种情况,这是:

print(myCards for myCards in self.cards)

is printing a generator expression, which is represented as: 正在打印生成器表达式,其表示为:

<generator object <genexpr> at 0x2256fa0>

For your third case, which prints each item in that object rather than printing the object itself, you can unpack your generator expression above with * and specify a custom separator: 对于第三种情况,它打印该对象中的每个项目而不是打印对象本身,您可以在上面用*解压缩生成器表达式并指定自定义分隔符:

print(*(myCards for myCards in self.cards), sep='\n')

Of course, note that you are once again copying that list for no reason. 当然,请注意,您将无缘无故再次复制该list Just use the original one instead of spending time and effort (both yours and the computer's) making a new one. 只需使用原始的而不是花费时间和精力(包括您和计算机的时间和精力)来制作新的。

print(*myCards, sep='\n')

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

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