简体   繁体   English

Python使用append写入Tuple Error

[英]Python Write to Tuple Error with append


I'm practicing Python 3.3.2 and I would like to practice the append technique to a tuple. 我正在练习Python 3.3.2,我想将附加技术练习到一个元组。
I have a text file named user_scores.txt. 我有一个名为user_scores.txt.的文本文件user_scores.txt. and it consists of scores from people in my workplace that they have submitted for a mathematical problem. 它包含了我们工作场所中提交数学问题的人的分数。 They have submitted different answers that they could produce. 他们提交了可以产生的不同答案。 The file is shown below (Alex only submitted two): 该文件如下所示(Alex仅提交了两个):

Alex, 35, 39
Daniel, 34, 35, 36 
Richard, 21, 23, 24

I am trying to write these scores to a tuple in this form: 我试图将这些分数写成这种形式的元组:

Name:Score, Score, Score.

So for example: 例如:
Alex:35, 39,
Daniel:34, 35, 36

I have attempted this with the code below, but it does not work as it returns the error underneath: 我已尝试使用下面的代码,但它不起作用,因为它返回下面的错误:

user_scores = []

with open('user_scores.txt') as f:
    for line in f:
        worker,score = line.strip().replace("\n","").split(",")
        user_scores[worker].append(int(score))

The error: 错误:

ValueError: too many values to unpack (expected 2)

What is the fix? 修复是什么? Is my block of code completely wrong or what? 我的代码块是完全错误还是什么?

Thanks, Dora. 谢谢,多拉。

First let's fix your data structure. 首先让我们修复您的数据结构。 You're referring to each score-tuple by test-taker name. 你指的是考生名字的每个得分元组。 Referring to values by a key (rather than by an index) is done using a dictionary. 通过键(而不是索引)引用值是使用字典完成的。

user_scores = dict() # or = {}. Same difference.

Then we know two things: 然后我们知道两件事:

  1. That the first item each line will be the name of the test-taker 每行的第一项将是考生的名字
  2. That there will be some number of scores thereafter, which will all be integers 之后会有一些分数,这些分数都是整数

So we can iterate through the file like this: 所以我们可以像这样遍历文件:

with open('path/to/file.txt') as infile:
    for line in infile:
        name, *scores = line.strip().split(',')

The glob there * instructs Python that there will be lots of these, so make a tuple of equivalent size. 那里的glob *指示Python会有很多这样的,所以制作一个相同大小的元组。 a, *b = (1, 2, 3, 4, 5) makes a = 1; b = (2, 3, 4, 5) a, *b = (1, 2, 3, 4, 5)使a = 1; b = (2, 3, 4, 5) a = 1; b = (2, 3, 4, 5) . a = 1; b = (2, 3, 4, 5) Now it's an easy thing to assign your values! 现在分配你的价值观很容易!

user_scores[name] = [int(score) for score in scores]

Note that this creates a list, not a tuple, but that's LIKELY what you want anyway. 请注意,这会创建一个列表,而不是一个元组,但这可能是你想要的。 Tuples indicate that the position of each element isn't just important but it HAS MEANING. 元组表明每个元素的位置不仅重要,而且还有意义。 This is easily explained by a point in the 2-D coordinate plane expressed as an ordered pair 这可以通过表示为有序对的2-D坐标平面中的点来容易地解释

#x, y
(1, 10)

is much different from 与...有很大的不同

#x , y
(10, 1)

In a list, it might be important that the list keep its order, but all of the elements MEAN the same thing. 在列表中,列表保持其顺序可能很重要,但所有元素都是相同的。 That's your use case here -- they're all scores, and you might want to correlate that each test-taker improved over time, but ultimately if a test score got moved to a different position, it doesn't change the fact that it's still a test score. 这是你的用例 - 他们都是得分,你可能想要关联每个考生随着时间的推移而改善,但最终如果考试成绩被转移到不同的位置,它不会改变它的事实还是一个考试成绩。

It looks like you're trying to write to a list, not a tuple. 看起来你正在尝试写一个列表,而不是一个元组。 Tuples are immutable, so this wouldn't be possible anyway. 元组是不可变的,所以无论如何这都是不可能的。 It also looks like you'd be trying to index the list by a string. 看起来你也试图用字符串索引列表。 This isn't possible, because lists require indexing by number. 这是不可能的,因为列表需要按编号索引。 I think what you want is a dict. 我想你想要的是一个字典。

Also, when you do 而且,当你这样做

worker, score = [list of things]

python expects list of things to have 2 items in it. python期望列表中包含2个项目。 You're apparently going to have a variable number of things. 你显然会有不同数量的东西。

Try this: 尝试这个:

user_scores = {}

with open('user_scores.txt') as f:
    for line in f:
        this_line = line.strip().replace("\n","").split(",")
        user_scores[this_line[0]] = this_line[1:]

This will create a dict that you can access by a person's name, and get back a list of their scores, no matter how many things are in the list. 这将创建一个你可以通过一个人的名字访问的字典,并获取他们的分数列表,无论列表中有多少东西。 For each line, it will split all of the things in the line by commas, make the key the person's name, and make the value a list of their scores. 对于每一行,它将用逗号分隔行中的所有内容,将键作为人名,并使值成为其分数的列表。

If you want the scores to be stored as numbers rather than strings, replace that last line with: 如果您希望将分数存储为数字而不是字符串,请将最后一行替换为:

user_scores[this_line[0]] = [int(score) for score in this_line[1:]]

Using a list in this case is better than using a tuple to store the scores because one can append to a list, a mutable type, but not to a tuple, an immutable type. 在这种情况下使用列表比使用元组存储分数更好,因为一个可以附加到列表,一个可变类型,但不是一个元组,一个不可变类型。

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

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