你的程序应该读取一个由L个整数组成的序列,每个整数都是N,用空格隔开。
输入40 40 40 29 29 29 17 17 17 92 92 92 86 86 86
输出4 40 8 29 2 17 5 92 10 86
line = input('Please enter the sequence: ').split()
list = []
for value in line:
print('\nvalue -', value)
count = 0
while value in line:
if value == '17':
print('found')
if line[0] == '17':
print('is here')
del line[0]
count += 1
print('\ninside value -', value, ' count - ', count)
print('\n', line)
list.extend([count, value])
print('\n', list)
这是一个简单的问题,但注意数字17,如果序列是2个或更少的数字,它不被计数,如果它至少有3个数字,它通常被计数。有人能解释一下问题出在哪里吗?我检查了好几次,都不明白。我已经找到了一个更好的解决方案,但我仍然想知道上面的Python代码中存在什么问题。谢谢!
发布于 2018-06-03 02:45:42
在不使用任何库的情况下,可以使用(分步过程)完成此操作:
_input = "40 40 40 40 29 29 29 29 29 29 29 29 17 17 92 92 92 92 92 86 86 86 86 86 86 86 86 86 86"
# transforming the raw values into a list/array
number_array = [int(i) for i in _input.split(' ')]
# returns unique values from input
number_unique = []
for na in number_array:
if na not in number_unique:
number_unique.append(na)
pass
# counts how many times the values appeared on the list, respectively
number_count = []
for n in number_unique:
number_count.append(number_array.count(n))
# pairing of the count and the unique value
res = []
for nc, nu in zip(number_count, number_unique):
res.append("{} {}".format(nc, nu))
print(' '.join(res))
# 4 40 8 29 2 17 5 92 10 86
# concatenating using join
https://stackoverflow.com/questions/50659474
复制相似问题