另一种计算两个列表之间频率的方法,无需计数

时间:2017-03-02 15:17:35

标签: python list while-loop

我创建了以下代码来检查第一个列表中的频率与不使用count的第二个列表相比:

F = [4,7,2]
N = [2,3,4,2,5,6,3,2,6,7,3,4]
frequency = [0,0,0]
for i in range(len(F)):
    for num in N:
        if F[i] == num:
            frequency[i]+=1
print('4 occurs in N', frequency[0], 'times')
print('7 occurs in N', frequency[1], 'times')
print('2 occurs in N', frequency[2], 'times')
print()

代码正确输出:

4 occurs in N 2 times
7 occurs in N 1 times
2 occurs in N 3 times

有没有其他方法可以在不使用count的情况下执行此操作?我正在尝试while循环,但它没有用。任何帮助表示赞赏。

5 个答案:

答案 0 :(得分:2)

您可以使用set来实现高性能。

from collections import defaultdict

F = [4,7,2]
N = [2,3,4,2,5,6,3,2,6,7,3,4]

set_f = set(F)
freq = defaultdict(int)

for num in N:
    if num in set_f:
       freq[num] += 1

print freq

Ta da!

Out: defaultdict(<type 'int'>, {2: 3, 4: 2, 7: 1})

答案 1 :(得分:0)

首先,def counter(sequence): counts = {} for item in sequence: counts[item] = counts.get(item, 0) + 1 return counts 经过高度测试,高效且是STL的一部分,请使用它!

>>> counter([2,3,4,2,5,6,3,2,6,7,3,4])
{2: 3, 3: 3, 4: 2, 5: 1, 6: 2, 7: 1}
>>> counter([4,7,2])
{2: 1, 4: 1, 7: 1}

其次,您可以建立自己的:

enif_consume_timeslice()

示例输出:

// HelloWorld.vue   
export default {
  data () {
    return {
      msg: 'Hello'
    }
  }
}

答案 2 :(得分:0)

你说“不使用Count”,所以我说这符合要求:

from collections import  Counter
F = [4,7,2]
N = [2,3,4,2,5,6,3,2,6,7,3,4]
counter = Counter(N)
for n in F:
    print(n, 'occurs in N', counter[n], 'times')

答案 3 :(得分:0)

您可以使用字典存储频率:

F = [4,7,2]
N = [2,3,4,2,5,6,3,2,6,7,3,4]
# Create the initial frequency dictionary
frequency = {}
for item in F:
    frequency[item] = 0

# Count the occurences
for item in N:
    if item in frequency:
        frequency[item] += 1

# Print the occurences
for item in F:
    print('{} occurs in N {} times'.format(item, frequency[item]))
print()

或者如果您希望它更短:

frequency = dict.fromkeys(N, 0)
for item in N:
    frequency[item] += 1
for item in F:
    print('{} occurs in N {} times'.format(item, frequency[item]))
print()

答案 4 :(得分:0)

在这篇文章中为多个用户分组解决方案,以便轻松找到它们。

解决方案1:collections.Counter

from collections import Counter

F = [4,7,2]
N = [2,3,4,2,5,6,3,2,6,7,3,4]

times = Counter(N)

for each in F:
    print("{} occurs in N {} times".format(each, times[each]))

解决方案2:list.count()

F = [4,7,2]
N = [2,3,4,2,5,6,3,2,6,7,3,4]

for each in F:
    print("{} occurs in N {} times".format(each, N.count(each)))

解决方案3:for循环

F = [4,7,2]
N = [2,3,4,2,5,6,3,2,6,7,3,4]

times = {each: 0 for each in F}

for each in N:
    if each in times:
        times[each] += 1

for item, frequency in times.items():
    print("{} occurs in N {} times".format(item, frequency))