我应该使用列表推导而不是常规的for循环吗?

时间:2020-02-11 20:04:01

标签: python python-3.x for-loop list-comprehension

问题

一家企业希望开发一个应用程序,以帮助贴纸收集者跟踪他们所拥有的卡片,贴纸组合在一起的许多贴纸,有时收集者会得到重复的卡片,而最重要的是贴纸被认为是稀有。

条目

第一行的X整数表示购买的贴纸,第二行的Y整数表示稀有贴纸。

退出

只有一行包含剩余的数字。

解决方案

for循环方法:

bought_stickers = [int(i) for i in input().split()]
rare_stickers = [int(i) for i in input().split()]

rare_stickers_left = len(rare_stickers)

for i in rare_stickers:
    if i in bought_stickers:
        rare_stickers_left -= 1

print(rare_stickers_left)

列表理解方法:

bought_stickers = [int(i) for i in input().split()]
rare_stickers = [int(i) for i in input().split()]

rare_stickers_left = [i for i in rare_stickers if i not in bought_stickers]
print(len(rare_stickers_left))

我的问题是,哪种解决方案是最佳的考虑因素,可读性,有效性和所有方面?

还有,哪种编码更适合奥林匹克竞赛?

3 个答案:

答案 0 :(得分:4)

都不是:Python的方法只是计算发生次数,而不是重新列出大型对象。

rare_stickers_left = sum(i not in bought_stickers for i in rare_stickers)

这只是将所有True个结果(取为1)加起来。

另一种可能性是进行设置并采用设置差异:

rare_stickers_left = len(set(rare_stickers) - set(bought_stickers))

但是,这样做的开销是制作三组并在临时组上调用len

答案 1 :(得分:1)

列表理解为:

  • 更简洁
  • 更多“ Pythonic”
  • 效率更高(避免不必要的变量查找)
  • 更简单,因此出错的机会更少

答案 2 :(得分:1)

这里不需要前两个for loops

bought_stickers = input().split()
rare_stickers = input().split() 
rare_stickers_left = [int(i) for i in rare_stickers if i not in bought_stickers]
print(len(rare_stickers_left))