python - 如果 __ 和 __ 在 ___ 那么

标签 python list if-statement dictionary

我正在尝试创建一个循环遍历列表的脚本。

我需要查看能力标识符的有限列表 (400)(例如 124、129 等 - 普通整数)

然后我有一本字典,记录每个用户拥有的能力。键是用户名,每个键的值是整数列表(即用户具有哪些能力)

例如

User x - [124, 198, 2244 ...]
User Y - [129, 254, 198, 2244 ...]

我希望编制一个矩阵,突出显示每项能力与其他所有能力发生的频率 - 邻接矩阵。

例如,在上面的示例中,能力 198 与能力 2244 出现了两次。而能力 254 和 124 从未同时出现过。

我目前正在使用这段代码:

fe = []    
count = 0
competency_matches = 0
for comp in competencies_list:
    common_competencies = str("")
for comp2 in competencies_list:
    matches = int(0)
    for person in listx:
        if comp and comp2 in d1[person]:
            matches = matches + 1
        else:
            matches = matches
    common_competencies = str(common_competencies) + str(matches) + ","
fe.append(common_competencies)
print fe
print count
count = count + 1

这不起作用,只会返回每种能力总体出现的次数。我认为问题在于“if comp and comp2 in d1[person]:”这一行。

问题是,例如,如果一个人具有以下能力 [123、1299、1236],而我搜索能力 123,由于它出现在 123 和 1236 条目中,因此将返回两次。在使用 if __ 和 __ then 操作时是否存在强制完全匹配的方法。

或者有没有人对如何实现这一点有改进的建议......

在此先感谢您的指点。干杯

最佳答案

您误解了 的工作原理。要测试两个值是否在列表中,请使用:

if comp1 in d1[person] and comp2 in d1[person]:
  ...

你的版本做了别的事情。它像这样绑定(bind):if (comp1) and (comp2 in d1[person])。换句话说,它将 comp1 解释为真值,然后用您的列表包含检查执行 bool 值 and。这是有效的代码,但它不会执行您想要的操作。

关于python - 如果 __ 和 __ 在 ___ 那么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5625013/

相关文章:

c# - 返回列表中对象的正确方法

javascript - if else javascript中的多个isNaN

html - CSS 继承其他的吗?

python - 导入错误 : cannot import name 'open_filename' from 'pdfminer.utils'

python - 如何从 Pandas 数据框中检索在其中一列末尾包含特定值的记录序列?

C# - 将列表转储到下拉列表

c# - XmlSerializer 序列化泛型接口(interface)列表

PHP-如何摆脱 "Undefined index"

python - 自定义 kivy 事件问题

Python Sphinx 自动摘要 : failed to import module