python - 如何访问每一行熊猫字典的值
问题描述
我从数据集创建字典,现在我想访问字典的每一行。这本词典的每一行都包含 2 个名字,例如:Winner: Alex Loser: Leo。我的问题是我不知道如何通过索引访问这两个名称。
我想要这样的东西:
第 1 行:获胜者:Alex Loser:Leo,我想访问这样的行: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)
在这里您可以看到数据集是如何构建 的。提前感谢您的帮助。
解决方案
让我们设置一个测试字典:
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)
我们可以使用 enumerate 函数添加行号:
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_dictionary 的长度范围并直接访问元素:
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])
推荐阅读
- java - 水平缩放的 Itextpdf 设置无效
- php - 哪里等于零这么慢
- java - 比较三个变量并返回具有最小值/最大值的变量(不是值)
- php - 为带有对象(SimpleXMLElement)的foreach()提供的PHP无效参数
- google-chrome - 从 chrome 中的“内容设置/通知”部分获取所有被阻止和允许的站点列表
- entity-framework - System.InvalidOperationException:在应用程序配置文件中找不到名为“xxx”的连接字符串
- node.js - node.js InApp 和调度
- java - 解析 JSON 时出错,POST 在 JSON 开头包含 \r\n
- sql - SQL 根据初始选择选择后续值
- node.js - 如何将 ElementHandle 移动到另一个页面