gpt4 book ai didi

python - 如果我使用 Dicts 名称创建变量,如何在 dict 中查找值?

转载 作者:行者123 更新时间:2023-11-30 23:46:38 25 4
gpt4 key购买 nike

用代码更容易解​​释:

#test data
Day1={
'data1':0,
'data2': 1,
'data3': 2,
'data4': 3,
'data5': 4,
'data6': 5,
'data7': 4,
'data8': 3,
'data9': 2,
'data10': 1}

Day2= {
'data1': 2,
'data2': 3,
'data3': 4,
'data4': 5,
'data5': 6,
'data6': 6,
'data7': 7,
'data8': 6,
'data9': 4,
'data10': 3}

Day3= {
'data1': 2,
'data2': 4,
'data3': 5,
'data4': 6,
'data5': 7,
'data6': 6,
'data7': 8,
'data8': 6,
'data9': 5,
'data10': 4}

Day4= {
'data1': 2,
'data2': 4,
'data3': 5,
'data4': 6,
'data5': 7,
'data6': 6,
'data7': 6,
'data8': 8,
'data9': 5,
'data10': 4}

AllData= {'Day1':Day1,'Day2':Day2,'Day3':Day3,'Day4':Day4}


#Number of items in AllData dictionary
AllDataSize = len(AllData)
CurrentDayCounter=0

while CurrentDayCounter < AllDataSize:
CurrentDayCounter=CurrentDayCounter+1
CurrentDay = 'Day%s' % (CurrentDayCounter)
#print AllData[CurrentDay]
#add the nodes
for day in AllData[CurrentDay]:
print CurrentDay
day = "%s" % (day)
print CurrentDay[day] #does not work gives an error: TypeError: string indices must be integers, not str
print CurrentDay[1] #works by providing a result 'a', which is the second letter in Day
#print 'For ', CurrentDay, ' subgroup ', day,' contains ', CurrentDay[day], ' has been added to graph.'
dayName = "%s-%s" % (CurrentDay, Day1[day])
#Do not create edges if its the first day
if CurrentDay != "Day1":
yesterday = CurrentDayCounter - 1
print 'today is ', CurrentDayCounter, ' and yesterday is ', yesterday

当我打印 CurrentDay[day] 时,出现错误: TypeError: stringindexs Must be integers, not str 但 CurrentDay[1] 给出的结果是(这是变量的中间字母。我想使用该变量来搜索字典,而不是拉出字母位置。

我怀疑我这样做是完全错误的,那么有正确的方法吗?

谢谢!附注抱歉,代码很糟糕,我只是在玩networkx,我想我删除了对它的所有引用,但如果我错过了任何内容,请忽略它。

最佳答案

第 (65) 行应该是:

print AllData[CurrentDay][day] 

出现错误消息的原因是 print CurrentDay[day] 打印字符串 CurrentDay 中的第 day 个字符

关于python - 如果我使用 Dicts 名称创建变量,如何在 dict 中查找值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8813036/

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