首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >python for while inside

python for while inside
EN

Stack Overflow用户
提问于 2018-06-03 01:30:54
回答 1查看 66关注 0票数 0

你的程序应该读取一个由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

代码语言:javascript
复制
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代码中存在什么问题。谢谢!

EN

回答 1

Stack Overflow用户

发布于 2018-06-03 02:45:42

在不使用任何库的情况下,可以使用(分步过程)完成此操作:

代码语言:javascript
复制
_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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50659474

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档