指令值()没有提供python中的所有值

2024-04-18 02:08:28 发布

您现在位置:Python中文网/ 问答频道 /正文

那个指令值()不提供在for循环中检索到的所有值。我使用for循环从文本文件中检索值。你知道吗

    test = {}

    with open(input_file, "r") as test:
        for line in test:
           value = line.split()[5]
           value = int(value)
           test[value] = value
           print (value)

   test_list = test.values()
   print (str(test_list))

值和测试值不包含相同数量的数据

输出如下:

打印“值”:

88
53
28
28
24
16
16
12
12
11
8
8
8
8
6
6
6
4
4
4
4
4
4
4
4
4
4
4
4
2
2
2
2
2

来自打印测试列表:

list values:dict_values([16, 24, 2, 4, 53, 8, 88, 12, 6, 11, 28])

有没有办法把重复的值也包括在列表中?你知道吗


Tags: test列表forinputvalueaswithline
3条回答

这条线:

test[value] = value

不会将新值添加到test如果它是重复的,则只会覆盖旧值。所以所有的复制品都会被移除。values()调用真正返回了dict中剩余的所有内容

Dictionary键不能包含重复项。在执行test[value] = value时,会覆盖键value处的旧值。因此只能得到一组有限的值。你知道吗

样品测试可以

>>> {1:10}
{1: 10}
>>> {1:10,1:20}
{1: 20}

在这里您可以看到,复制键被新值覆盖

评论后编辑

正如您所说的您想要一个值列表,您可以在开始处有一个语句l = [],在有test[value] = value的地方有l.append(value)

这是因为python字典不能有重复的值。每次运行test[value] = value时,它都会替换现有值,或者在字典中还没有的情况下添加该值。你知道吗

例如:

>>> d = {}
>>> d['a'] = 'b'
>>> d
{'a': 'b'}

>>> d['a'] = 'c'
>>> d
{'a': 'c'}

我建议你列个清单,比如:

output = []

with open(input_file, "r") as test:
    for line in test:
       value = line.split()[5]
       value = int(value)
       output.append(value)
       print (value)

print (str(output))

相关问题 更多 >