在python中解压缩变量

时间:2014-02-28 21:24:41

标签: python

完整代码:

scores = []
choice = None

while choice != "0": #while choice isnt 0 options will be printed to user and
#the user will have an opportunity to pick a choice 0-2
    print("""
    High Scores 2.0

    0 - Quit
    1 - List Scores
    2 - Add a Score
    """)

    choice = input("Choice: ")
    print()

    #display high-score table
    if choice == "1":
        print("High Scores\n")
        print("NAME\tSCORE")
        for entry in scores: 
            score,name = entry
            print(name, "\t", score)

    #add a score
    elif choice == "2":
        name = input("What is the player's name: ")
        score = int(input("What score did the player get: "))
        entry = (score, name)
        scores.append(entry)
        scores.sort(reverse = True)
        scores = scores[:5] #Keeps only top 5 scores

#exit
if choice == "0":
    print("Goodbye")

我的问题是为什么:

for entry in scores: 
    score,name = entry
    print(name, "\t", score)

for entry in scores: 
        entry= score,name
        print(name, "\t", score)

两者都正常工作? 我在打开包装时非常困惑,我不确定为什么这两段代码都能正常工作,有人可以解释一下吗?

3 个答案:

答案 0 :(得分:0)

  

我的问题是为什么:

for entry in scores: 
    score,name = entry
    print(name, "\t", score)
  

for entry in scores: 
        entry= score,name
        print(name, "\t", score)
  

工作正常吗?

第一个正常工作并且是有效的python,但第二个不应该工作。它应该提出NameError,说scorename不存在。

关于第一个解包,也称为解构分配,其工作原理如下:

在右侧你有一个可迭代的,在左侧有一个元组,左手边的每个元素元组受到 iterable 元素的影响。如果要分配的元素太多,则会得到ValueError: too many elements to unpack

即:

>>> mylist = [1,2,3]
>>> foo, bar, foobar = mylist
>>> print foo, bar, foobar
1 2 3

相当于:

>>> foo, bar, foobar = [1,2,3]
>>> print foo, bar, foobar
1 2 3

就这么简单!

修改

基本上,你真正做的是:

for entry in scores:
    print entry # here you shall see something like `('value1', 'value2')`
    score,name = entry
    print(name, "\t", score)

每个条目都是(至少)两个值的元组,用于表示您用作分数和名称的内容。

阅读资源:

HTH

答案 1 :(得分:0)

您的两个代码段不会做同样的事情。

for entry in scores: 
    score,name = entry
    print(name, "\t", score)

此代码段将entry解压缩到两个变量scorename中,这可能是您想要的。

for entry in scores: 
    entry= score,name
    print(name, "\t", score)

另一方面,此代码段会为变量(score,name)分配元组entry。我无法想象这就是你想要的。

答案 2 :(得分:0)

这样做会更简单:

scores = [(10, 'Alice'), (5, 'Bob')]
for score, name in scores: 
    print(name, "\t", score)

结果:

10   Alice
5   Bob