下面的代码查看名为pair的tuple
s(每个都有两个元素)列表,并在列表中创建一个包含所有元素名称的库。然后计算任何元素出现在tuple
中的次数,并将其除以多个元素。我想要整个list
的每个元素的平均交互次数(它在元组中出现的次数与另一个元素的次数)。
def average(pairs):
intcount = 0
bank = []
for j,k in pairs:
if not j in bank:
bank.append(j)
if not k in bank:
bank.append(k)
if j in bank:
intcount += 1
if k in bank:
intcount += 1
output = intcount/len(bank)
return output
代码运作良好,但是是一个眼睛。我正在尝试学习如何编写更多的pythonic代码,但每当我尝试将代码压缩成更少的行时,它就会变得错误。我的糟糕尝试的一个例子:
def average(pairs):
intcount = 0
bank = []
if not j or k in bank for j,k in pairs:
bank.append(if not j in bank else k if not k in bank else ' ' for j, k in interactions)
#then some kind of line streamlining how the intcount increments?
答案 0 :(得分:1)
您可以使用set
。
def average(pairs):
bank, intcount = set(), 0
for j, k in pairs:
bank.update({j, k})
intcount += 1 if j in bank or k in bank
return intcount/len(bank)
答案 1 :(得分:0)
尝试这些两行
pairs = [(1,2), (2,3), (3,4), (4,5)]
bank = set(i for pair in pairs for i in pair) # {1, 2, 3, 4, 5}
output = 2*len(pairs) / len(bank) # 1.6
In [288]: output
Out[288]: 1.6
In [289]: average(pairs) # your function
Out[289]: 1.6
看看它是否适合你。