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

如何在Python中向数组中的特定单元格插入值?,python,arrays,Python,Arrays,我需要从用户那里得到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

我需要从用户那里得到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的值吗

谢谢,
亚尼夫

你可以用两种方法来做。使用字符串或整数

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”出现的次数,等等

def string_count(nums):
    # Make a long string with all the numbers stuck together
    s = ''.join(map(str, nums))

    # Make all of the digits into strings
    n = ''.join(map(str, range(10)))

    aDigits = [0,0,0,0,0,0,0,0,0,0]

    for i, x in enumerate(n):
        aDigits[i] = s.count(x)

    return aDigits
对于整数,我们可以使用可爱的整除技巧。这段代码是为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)]

您可以连接所有输入以获得单个字符串,并将其用于
collections.Counter()


提示:
range(0,10,1)==range(10)
谢谢你的回答,但是因为我是python新手,所以我不理解你写的大部分内容。有没有办法修复我的代码?我成功了:)我根据你写的东西修复了我的代码。非常感谢。
import collections
ct = collections.Counter("1234567890123475431234")
ct['3'] == 4
ct.most_common() # gives a list of tuples, ordered by times of occurrence