如何在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没有正常工作。当我写temp=aDigits[iLastNum]+1时,难道不应该表示数组中第iLastNum个位置的值加1吗?
谢谢,
Yaniv
2 个回答
0
你可以用两种方法来实现这个功能。要么用字符串,要么用整数。
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
用整数的方法我们可以利用整数除法这个好方法。这个代码是为Python 2.7写的,在3.x版本上不能用,因为有“假设为浮点数”的变化。要解决这个问题,把x /= 10
改成x //= 10
,同时把打印语句改成打印函数。
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)]
1
你可以把所有的输入连接起来,形成一个完整的字符串,然后用这个字符串来使用 collections.Counter()
。
import collections
ct = collections.Counter("1234567890123475431234")
ct['3'] == 4
ct.most_common() # gives a list of tuples, ordered by times of occurrence