简体   繁体   English

打印所有重复的数字

[英]print all repeated numbers

My intent is for this code to print out all repeated numbers and then state how many times each number is repeated.我的目的是让这段代码打印出所有重复的数字,然后说明每个数字重复的次数。

However, when I run the code, only the first repeated number is printed, displayed as (2, 5).但是,当我运行代码时,只打印第一个重复的数字,显示为 (2, 5)。 Since 9 is also a repeated number, I want both (2, 5) and (5, 9) to be printed.由于 9 也是一个重复的数字,我希望 (2, 5) 和 (5, 9) 都被打印出来。 What code modifications are needed?需要修改哪些代码?

You return as soon as you hit a value with a count greater than 1. Instead, map everything to a tuple of x and count (I reversed them).一旦遇到计数大于 1 的值,您就立即返回。相反,将所有内容映射到 x 和计数的元组(我将它们颠倒了)。 And validate the count after the fact.并在事后验证计数。 Something like就像是

i = [5,5,7,9,9,9,9,9]
def num_list(i):
    return [(x,i.count(x)) for x in set(i)]

for tv in num_list(i):
    if tv[1] > 1:
        print(tv)

And I get我得到

(9, 5)
(5, 2)

Because there are 5 nines and 2 fives.因为有 5 个 9 和 2 个 5。

You're returning when a single duplicate value is found.当找到单个重复值时,您将返回。 After then it's not checking the whole array.之后它不会检查整个数组。 Use a set() and add if found any duplicate value and return it to the end of the loop.使用set()并在发现任何重复值时添加并将其返回到循环的末尾。

i = [5,5,7,9,9,9,9,9]
def num_list(i):
    s=set()
    for x in (i):
        if i.count(x) > 1:
            s.add( (i.count(x), x))
    return s
print(num_list(i))

Output输出

{(5, 9), (2, 5)}

If you are only looking for repetitions anywhere in the list, then you can use the Counter class from collections which will count the number of each distinct value in the list:如果您只是在列表中的任何地方寻找重复,那么您可以使用集合中的 Counter 类,它将计算列表中每个不同值的数量:

i = [5,5,7,9,9,9,9,9]

from collections import Counter
r = [(c,n) for n,c in Counter(i).items() if c>1]

print(r)
[(2, 5), (5, 9)]

If you want to count streaks of repeating numbers, the the groupby function, from itertools can help by returning groups of consecutive identical values:如果要计算重复数字的连续数,itertools 中的 groupby 函数可以通过返回连续相同值的组来提供帮助:

i = [5,5,7,9,9,7,7,7,9,9,9]

from itertools import groupby
r = [ (c,n) for n,g in groupby(i) for c in [len([*g])] if c>1]

print(r)
[(2, 5), (2, 9), (3, 7), (3, 9)]

just只是

data = [5, 5, 7, 9, 9, 9, 9, 9]
output = [(x, data.count(x)) for x in set(data)]

print(output)

output:输出:

[(9, 5), (5, 2), (7, 1)]

-- ——

Update:更新:

I think standard for loop will be more proper.我认为标准 for 循环会更合适。

data = [5, 5, 7, 9, 9, 9, 9, 9]
output = []
for x in set(data):
    output.append(x)
    output.append(data.count(x))
    
print(output)

output:输出:

[9, 5, 5, 2, 7, 1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM