加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python:处理两个列表的“Pythonic”方法是什么?

发布时间:2020-12-20 12:23:42 所属栏目:Python 来源:网络整理
导读:说我在 Python中有这个代码.我是Perl程序员,你可能会说. # Both list1 and list2 are a list of stringsfor x in list1: for y in list2: if y in x: return Truereturn False 有什么更Pythonic的方法来处理这个问题?我认为列表理解可以做得很好,但我无法理
说我在 Python中有这个代码.我是Perl程序员,你可能会说.

# Both list1 and list2 are a list of strings
for x in list1:
  for y in list2:
    if y in x:
      return True
return False

有什么更Pythonic的方法来处理这个问题?我认为列表理解可以做得很好,但我无法理解这个“过程两个单独的列表”的一部分.

解决方法

要将两个嵌套循环转换为嵌套理解,您只需执行以下操作:

[<expression> for x in list1 for y in list2]

如果您从未想过列表推导如何工作,那么教程explains it:

A list comprehension consists of brackets containing an expression followed by a for clause,then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.

换句话说,理解中从左到右的条款与从顶部/外部到底部/内部的陈述相匹配,这就是它的全部内容.

This blog post试图以另一种方式提出相同的想法,以防你尚未得到它.

但是在这里,你没有表达,你有一个声明.

但是你有一个表达式,声明的x部分中的y,你要做的是返回True,如果它对任何值都是真的,这正是任何做的.所以:

return any([y in x for x in list1 for y in list2])

实际上,您不希望在此处构建列表,只是迭代值,因此删除方括号以使其成为生成器表达式:

return any(y in x for x in list1 for y in list2)

对于只迭代多个迭代的笛卡尔积的简单情况,您可能想要使用itertools.product.在这种情况下,我认为它不会使事情变得更简单或更具可读性,但如果你有四个列表而不是两个 – 或者预先不可预测的数量 – 这可能是一个不同的故事:

return any(y in x for x,y in product(list1,list2))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读