gpt4 book ai didi

python - 具有元组键和两个列表作为值的字典,其中一个值仅添加到列表之一

转载 作者:行者123 更新时间:2023-12-05 03:29:08 25 4
gpt4 key购买 nike

我有一组元组形式的整数构成我的键 (a,b)。我需要构建一个字典,其中对于每个键,一个值( float )被放入充当对值的两个列表之一:

(a,b) : [x_list,y_list]

我正在从一个 txt 文件构建字典,其中每一行都有元组 (a,b)xy 之一> - 应添加到列表中的类型值。但是,我不明白如何做到这一点。

更准确地说:

如果txt文件包含:

15,17,x_type,-1.1
15,17,y_type,44
1,2,y_type,-0.38
15,17,y_type,5

字典应该产生

d: {(1,2): [[], [-0.38]] , (15,17): [[-1.1], [5,44]]

我正在尝试:

example = ['15,17,x_type,-1.1','15,17,y_type,44','1,2,y_type,-0.38','15,17,y_type,5']

for _ in example:
[a,b,val_type,val] = _.split(',')
if val_type == 'x_type':
d[(a,b)] = [val,]
if val_type == 'y_type':
d[(a,b)] = [,val]

语法允许 [x,],但不允许 [,y]。为什么?

最佳答案

列表可以包含尾随逗号。 [x,][x] 相同。要附加到特定的嵌套列表,请按索引选择所需的列表:

if type == 'x_type':
d[(a,b)][0].append(x)
elif type == 'y_type':
d[(a,b)][1].append(y)

这假设您一遇到键就创建一个新的嵌套列表:

if (a, b) not in d:
d[a, b] = [[], []]

另一个不错的句法技巧是,索引表达式中带有逗号的任何内容都被解释为元组。这意味着您可以将 d[(a, b)] 写成 d[a, b]

关于python - 具有元组键和两个列表作为值的字典,其中一个值仅添加到列表之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71072966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com