尝试在长列表中找到唯一的数字,然后按顺序返回。 (上一个版本不起作用)

发布于 2025-02-12 08:52:18 字数 501 浏览 1 评论 0原文

您可能会认为这个问题是上述的。回答,但最后一个版本与2位数字无效 给定数字列表,查找并打印仅出现一次的元素。这些元素应按照原始列表中出现的顺序打印。

因此,这是我的代码(由其他pythoneer修复),

a = [int(s) for s in input().split()]
sortedLst = sorted(a)
unique = []
uniqueOrd = []

for i in range(len(a) - 2):
     if sortedLst[i + 1] != sortedLst[i] and sortedLst[i + 1] != sortedLst[i + 2]:
            unique.append(sortedLst[i + 1])

for num in a:
    if num in unique:
        uniqueOrd.append(num)

print(*uniqueOrd)

但是输出不适合2位数字编号,我该如何修复此错误?

You may consider this question is prev. answered, but the last version doesn't work with 2 digits number
Given a list of numbers, find and print the elements that appear in it only once. Such elements should be printed in the order in which they occur in the original list.

so here's my code (being fixed by other pythoneers)

a = [int(s) for s in input().split()]
sortedLst = sorted(a)
unique = []
uniqueOrd = []

for i in range(len(a) - 2):
     if sortedLst[i + 1] != sortedLst[i] and sortedLst[i + 1] != sortedLst[i + 2]:
            unique.append(sortedLst[i + 1])

for num in a:
    if num in unique:
        uniqueOrd.append(num)

print(*uniqueOrd)

but the output does not work with 2 digits number, how can I fix this bug?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

青春如此纠结 2025-02-19 08:52:18

您不必为从长列表中找到唯一而努力工作,只需考虑collections - 计数器的nice lib即可。它更快,更柔软。

A = [int(s) for s in input().split()]
sortedLst = sorted(A)         # this is just to confirm your inputs..

from collections import Counter

counts = Counter(A)
print(counts)

uniques = [k for k, v in counts.items() if v == 1] # just check the frequency (v) 

print(uniques)

尝试一些输入,例如:2 3 1 4 22 33 44 55 33 22

[2, 3, 1, 4, 44, 55]

You don't have to labor yourself on finding the uniques from a long list, just consider the nice lib from collections - Counter. It's faster and more Pythonic.

A = [int(s) for s in input().split()]
sortedLst = sorted(A)         # this is just to confirm your inputs..

from collections import Counter

counts = Counter(A)
print(counts)

uniques = [k for k, v in counts.items() if v == 1] # just check the frequency (v) 

print(uniques)

Try some inputs like: 2 3 1 4 22 33 44 55 33 22

[2, 3, 1, 4, 44, 55]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文