如何在Python中向数组中的特定单元格插入值?

2024-06-24 13:19:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从用户那里得到10个数字,然后计算出每个数字出现在所有数字中的次数。在

我写了下一个代码:

# Reset variable
aUserNum=[]
aDigits=[]

# Ask the user for 10 numbers
for i in range(0,2,1):
    iNum = int(input("Please enter your number: "))
    aUserNum.append(iNum)

# Reset aDigits array
for i in range(0,10,1):
    aDigits.append(0)

# Calc the count of each digit
for i in range(0,2,1):
    iNum=aUserNum[i]
    print("a[i] ",aUserNum[i])
    while (iNum!=0):
        iLastNum=iNum%10
        temp=aDigits[iLastNum]+1
        aDigits.insert(iLastNum,temp)
        iNum=iNum//10

print(aDigits)

从结果,我可以看出临时工不起作用。 当我写这个temp=aDigits[iLastNum]+1时,它不是应该说单元iLastNum中的数组将获得单元格+1的值吗?在

谢谢, 亚尼夫


Tags: the用户inforrange数字次数temp
2条回答

您可以将所有输入串联起来以获得一个字符串,并将其与collections.Counter()一起使用

import collections
ct = collections.Counter("1234567890123475431234")
ct['3'] == 4
ct.most_common() # gives a list of tuples, ordered by times of occurrence

你可以用两种方法。可以是字符串,也可以是整数。在

aUserNum = []

# Make testing easier
debug = True

if debug:
    aUserNum = [55, 3303, 565, 55665, 565789]
else:
    for i in range(10):
        iNum = int(input("Please enter your number: "))
        aUserNum.append(iNum)

对于字符串,我们将所有整数转换为一个大字符串,然后计算“0”的出现次数,然后计算“1”的出现次数,等等

^{pr2}$

对于整数,我们可以使用整数除法这个可爱的技巧。这段代码是为Python2.7编写的,由于“假定浮点”的更改,在3.x上不起作用。要解决这个问题,请将x /= 10更改为x //= 10,并将print语句更改为print函数。在

def num_count(nums):
    aDigits = [0,0,0,0,0,0,0,0,0,0]

    for x in nums:
        while x:
            # Add a count for the digit in the ones place
            aDigits[x % 10] += 1

            # Then chop off the ones place, until integer division results in 0
            # and the loop ends
            x /= 10

    return aDigits

这些输出相同。在

print string_count(aUserNum)
print num_count(aUserNum)
# [1, 0, 0, 3, 0, 9, 4, 1, 1, 1]

为了得到更漂亮的输出,请这样写。在

print list(enumerate(string_count(aUserNum)))
print list(enumerate(num_count(aUserNum)))
# [(0, 1), (1, 0), (2, 0), (3, 3), (4, 0), (5, 9), (6, 4), (7, 1), (8, 1), (9, 1)]

相关问题 更多 >