如何在Python中打印链表的元素?

2024-04-19 22:22:37 发布

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

例如,假设我有

node = {}
node['data'] = ['hi', '8']

newNode = {}
newNode['data'] = ['hello', '6']

我想比较node和newNode中的数字6和8

如果我试着

^{pr2}$

因为数字在列表的第1位,所以我得到一个错误信息:

KeyError: 1


Tags: nodehello列表data数字hikeyerrorpr2
2条回答

您可以将它们比较为:

node["data"][1] == newNode["data"][1]

通过打印node[1],实际上是在节点字典中搜索名为1的键。相反,由于您将其命名为“data”,请使用node['data'][1]node['data']['hi', '8']。如果8和6相同,则以下将打印True或False。在

node = {}
node['data'] = ['hi', '8']
# you can also create the dictionary by doing this:
# node = {'data' :  ['hi', '8']}
# or
# node = dict{'data' =  ['hi', '8']}

newNode = {}
newNode['data'] = ['hello', '6']

# so to compare:

print(node['data'][1]==newNode['data'][1])

相关问题 更多 >