【问题标题】:How I could write it better? Without Counter etc. libraries我怎样才能写得更好?没有 Counter 等库
【发布时间】:2015-12-06 19:57:21
【问题描述】:

您好,我正在学习 Python,我有一个问题要问您。我的脚本计算在数组中找到数字 0-9 的次数,并以 [[0,0],[1,0],[2,0].....] 格式保存数据。 ?没有任何库我怎么能写得更好?我想扩大 Python 知识的视野,提高自己的技能。

我的代码:

inp=input("Enter a sequence of numbers: ")
tab=[]
for i in range(0,10):
    counter=0
    for c in inp:
        if c == str(i):
            counter+=1
    tab.append([])
    tab[i].append(i)
    tab[i].append(counter)
print(tab)

示例输入

Enter a sequence of numbers: 111112222333445

输出

[[0, 0], [1, 5], [2, 4], [3, 3], [4, 2], [5, 1], [6, 0], [7, 0], [8, 0], [9, 0]]  

最好的问候

【问题讨论】:

  • 我没有看到这里使用了任何库...
  • 这是真的。但我希望看到这个问题的其他解决方案,比我的要好得多
  • 您想要优化的工作代码应该发布在 CodeReview 而不是 StackOverflow 上
  • @cricket_007 是的,看起来很适合 codereview
  • @SamiKuhmonen,这就是重点,不使用库就可以做到这一点

标签: python arrays counter


【解决方案1】:

很高兴阅读

inp = '111112222333445'
numbers = [int(number) for number in inp]
res = [[index, 0] for index in range(10)] 
for number in numbers:
    res[number][-1] += 1
print(res)

[[0, 0], [1, 5], [2, 4], [3, 3], [4, 2], [5, 1], [6, 0], [7, 0], [8, 0], [9, 0]]

在循环中转换为int

inp = '111112222333445'
res = [[index, 0] for index in range(10)] 
for number in inp:
    res[int(number)][-1] += 1

使用map

inp = '111112222333445'
res = [[index, 0] for index in range(10)] 
for number in map(int, numbers):
    res[number][-1] += 1

【讨论】:

  • 第2行也可以是map(int, inp)
  • @cricket_007 是的。还有更多变化。
  • @Rarez 你觉得这些有用吗?
【解决方案2】:

您也可以创建自己的 Counter dict 来使用常规 dict 进行计数:

inp = "111112222333445"

d = {}.fromkeys(range(10), 0)
for i in map(int, inp):
    d[i] += 1

print([[i, d[i]] for i in range(10)])
[[0, 0], [1, 5], [2, 4], [3, 3], [4, 2], [5, 1], [6, 0], [7, 0], [8, 0], [9, 0]]

如果顺序无关紧要并且您对元组没问题,只需致电list(d.items())

print(list(d.items()))

【讨论】:

    【解决方案3】:

    最简单的方法是在模块集合中使用类CounterCounter 是一个dict,用于存储某个项目在列表中或可迭代的次数。

    是这样的:

    from collection import Counter 
    inp=input("Enter a sequence of numbers: ") #str
    cuenta = Counter(inp) #{char:int}
    print(list(cuenta.items())) #[ (char,int) ] , items() give the contents of a dict in 
                                #tuples of the form (key,value) 
    

    使用Counter(inp),您将inp 视为一个字符列表,您也可以使用filter 删除inp 中的无数字字符,如下所示

    filter(lambda x:x.isdigit(),inp)
    

    然后将cuenta 更改为

    cuenta = Counter(filter(lambda x:x.isdigit(),inp))
    

    但如果你不想使用Counterfilter,因为函数式编程风格对你来说还是很陌生,那么与其使用列表,我宁愿使用dict 并像这样编写 Counter 为我所做的工作:

    inp=input("Enter a sequence of numbers: ") #str
    digit_count = dict( [ (n,0) for n in range(10) ] ) #inicialize this dict with the keys 
                                                       #that I care about and a value of zero, 
                                                       #meaning that a see none of them yet
    for char in inp:          #here I treat inp like a list of char
        if char.isdigit() :   #I make sure that is a number
            digit_count[ int(char) ] += 1 
    tab = list(digit_count.items())  
    print( tab )
    

    如果你真的需要 tab 成为列表列表,那么你可以这样做

    tab = list( list(elem) for elem in digit_count.items() )
    

    此外,您还可以像这样构建通用计数器函数

    def counter(iterable)
        """Function that return a list of the form [(item,count)] where
           item are the elements of iterable and count is how many times
           is present in there"""
        counter = dict()
        for elem in iterable:
            if elem in counter:
                counter[elem] += 1
            else:
                counter[elem] = 1
        return list(counter.items()) #or just return the counter
    

    这样做,您可以在其他可能需要的情况下重用此代码,而不必再次编写它,毕竟可修改性和可重用性是优秀程序员的标志

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 2011-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多