如何只在列表中循环一次关系?

时间:2009-09-14 10:19:01

标签: python

我有一个用户列表:

users = [1,2,3,4,5]

我想计算它们之间的关系:

score = compatibility( user[0], user[1] )

如何循环用户以便只计算一次用户之间的关系?

6 个答案:

答案 0 :(得分:11)

如果您只关心有序关系,您可以执行以下操作:

>>> for i, u in enumerate(users[1:]):
    print(users[i], u)           # or do something else


1 2
2 3
3 4
4 5

如果您需要所有组合,请使用itertools.combinations

>>> import itertools
>>> for i in itertools.combinations(users, 2):
    print(*i)

1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5

答案 1 :(得分:0)

用于循环或列表理解。

这里是循环示例:

for u in users:
    for su in users:
        if su == u:
            pass
        else:
            score = compatibility(u, su)
            # do score whatever you want

列表理解:

score = [compatibility(x, y) for x in users for y in users if x!=y and compatibility(x,y) not in score]

答案 2 :(得分:0)

以下内容应该有效(未经测试):

users_range = range(len(users))

# Initialize a 2-dimensional array
scores = [None for j in users_range for i in users_range]

# Assign a compatibility to each pair of users.
for i in users_range:
    for j in users_range:
        scores[i][j] = compatibility(users[i], users[j])

答案 3 :(得分:0)

我设法做了我想要的事情:

i = 0
for user1 in users:   
    i += 1     
    for user2 in users[i:]:
        print compatibility( user1, user2 )

答案 4 :(得分:0)

如果你的意思是:

compatibility(user[0], user[1]) == compatibility(user[1], user[0])

你可以使用:

for i, user1 in enumerate(users):
    for user2 in users[i:]:
        score = compatibility(user1, user2)

这也将计算相同用户之间的兼容性(可能适用)

答案 5 :(得分:0)

import itertools

def compatibility(u1, u2):
    "just a stub for demonstration purposes"
    return abs(u1 - u2)

def compatibility_map(users):
    return dict(((u1, u2), compatibility(u1, u2))
         for u1, u2 in itertools.combinations(users, 2))

> compat.compatiblity_map([1,2,3,4,5])
{(1, 2): 1, (1, 3): 2, (4, 5): 1, (1, 4): 3, (1, 5): 4,
 (2, 3): 1, (2, 5): 3, (3, 4): 1, (2, 4): 2, (3, 5): 2}

如果兼容性(a,b)与兼容性(b,a)不同,则使用itertools.permuations而不是itertools.combinations。