访问列表Python中的元素 [英] Accessing elements in a list Python

查看:92
本文介绍了访问列表Python中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的回答列表如下:

answers = defaultdict(<class 'list'>, {38: [0, 17], 19: [2], 5: [14], 3: [21], 1: [23, 32], 25: [26], 42: [28, 40], 34: [31], 12: [43, 46]})

现在,我尝试按如下所示连接点:

Now I'm trying to connect the points as follows:

for v in answers.values():
    if len(v)>1:
        T.add_edge(v[0],v[1])

这很好用,但是当Answers.values()的长度为1时,就像在(...., 19: [2], ...)中一样,我需要将2及其对应的类值(即19)连接起来.如何访问上面的answers列表中的类值?

This works fine, but when the length of answers.values() is 1, like in (...., 19: [2], ...) I need to connect 2 with its corresponding class value (which is 19). How can I access the class value in the above answers list?

推荐答案

您将需要跟踪该字典中的键和值,例如:

You will need to keep track of the keys and the value in that dict like:

for k, v in answers.items():
    if len(v) > 1:
        T.add_edge(v[0], v[1])
    else:
        T.add_edge(k, v[0])

这篇关于访问列表Python中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆