从python中的列表理解中仅打印列表的值

发布于 2025-01-29 16:53:20 字数 384 浏览 1 评论 0原文

考虑一下我有一个列表,n_list

n_list = [2, 4, 4, 5, 2]

我的目标是获取具有出现频率的唯一val在列表中仅为1。

我可以按以下方式做:

result = [val for val in n_list if n_list.count(val) == 1]
for i in result:
    print(i)

但是,我想获得列表中列表理解的结果,只是值。基本上,在没有为其编写单独的循环的情况下,这意味着没有:

for i in result:
    print(i)

使用列表理解。

Consider I have a list, n_list

n_list = [2, 4, 4, 5, 2]

My goal is get the unique val that has frequency of occurrence is only 1 in the list.

I am able to do as follows:

result = [val for val in n_list if n_list.count(val) == 1]
for i in result:
    print(i)

However, I would like to get the result of list comprehension with the list and just the value. Basically, without writing a separate for loop for it, that means, without:

for i in result:
    print(i)

but using list comprehension.

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

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

发布评论

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

评论(1

金橙橙 2025-02-05 16:53:21

只是发现了,我们可以使用*打印结果,

print(*[val for val in n_list if n_list.count(val) == 1])

但是,当作为函数测试时,它会产生错误:

def singleVal(n_list):
    return(*[val for val in n_list if n_list.count(val) ==1])
    
singleVal(n_list)

错误:在这里无法使用启动表达式。

Just figured out, we can print the result using *

print(*[val for val in n_list if n_list.count(val) == 1])

However, when tested as a function, it gives error:

def singleVal(n_list):
    return(*[val for val in n_list if n_list.count(val) ==1])
    
singleVal(n_list)

Error: Can’t use started expression here.

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