如何访问每一行的值

2024-09-28 22:20:15 发布

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

我从数据集创建了一个字典,现在我想访问字典的每一行。这本词典的每一行都包含两个名字,例如:胜者:亚历克斯失败者:利奥。 我的问题是,我不知道如何通过索引访问这两个名称

我想要这样的:
第一排:获胜者:亚历克斯 失败者:利奥 我想这样访问行:dictionary[x]->;所以我可以得到这一行,一旦我有了这一行,我想访问它,就像a=raw[y]和b=raw[y+1]。然后我想打印A和B。我想这样做是因为我必须从每一行复制一个特定的播放器,并将其保存到另一个字典中

这是我为创建字典和访问字典而编写的代码,但它不能按我所希望的那样工作

dicti= imd4.to_dict('index') // dicti  is the dictionary that I created and imd4 is the dataset containing the Winner and the Loser name
for x in dicti:
print (x,':')
for y in dicti[x]:
    a=dicti[x][y]
    b=dicti[x][y+1]    //I can't do this  but I would like to do it. So I can save the data base on their index 
    print (y,':',dicti[x][y])
    print('Test :' ,a)

Here you can see how the dataset is build 提前感谢您的帮助


Tags: andthetoforindexrawdictionary字典
1条回答
网友
1楼 · 发布于 2024-09-28 22:20:15

让我们设置一个测试字典:

test_dictionary=[
     {'winner':'ross','loser:'chandler'},
     {'winner':'rachael','loser:'phoebe'},
     {'winner':'joey','loser:'monica'},
     {'winner':'gunther','loser:'chandler'}
]

我们可以很容易地循环:

for contest in test_dictionary:
    print (contest)

我们可以使用枚举函数添加行号:

for line_number, contect in test_dictionary:
    print (line_number,contest)

现在我们有了行号,我们可以很容易地访问下一个元素-我们必须记住,虽然我们不想访问最终元素,因为在此之后我们无法打印比赛,所以我们循环到[-1]元素:

for line_number, contect in test_dictionary[:-1]:
    print (line_number,contest)
    print (line_number+1,test_dictionary[line_number+1])

我们也可以简单地使用test_字典长度的范围,直接访问元素:

for line_number in range(len(test_dictionary)-1]:
    print (line_number,test_dictionary[line_number])
    print (line_number+1,test_dictionary[line_number+1])

相关问题 更多 >