python - 如何从列表理解“转换”两者:for-in 和 if-in... 到带有循环和条件的“普通”python3 代码
问题描述
请不要关闭它,因为我是 py3 的新手。帮助我从列表理解“转换”:for-in 和 if-in... 到带有循环和条件的“普通”python3 代码:
为什么麻烦?因为坦率地说它会帮助我理解这两个概念,因为我刚开始使用 py3,这让我很焦虑......真的很糟糕。
# here is the original code that needs conversion...
friends = ["Wolf", "Frootie", "charlean", "Jenny"]
guests = ["xavier", "Bobbie", "wolf", "Charlean", "ashley"]
friends_lcase = [f.lower() for f in friends]
#guests_lcase = [g.lower() for g in guests]
present_friends = [
name.title() for name in guests if name.lower() in friends_lcase
]
print(present_friends)
# here below should be the equivalent of
# the above code, which is the issue for me...
# i tried the next but failed, help:
present_friends_2 = []
for i in friends:
if i.lower() in guests:
present_friends_2.append(i)
else:
present_friends_2.append(0)
print(present_friends_2)
解决方案
在您在这里提问之前,请花点时间查看一些 Python 方面的好书,例如 Dive into Python 3 。
friends = ["Wolf", "Frootie", "charlean", "Jenny"]
guests = ["xavier", "Bobbie", "wolf", "Charlean", "ashley"]
#friends_lcase = [f.lower() for f in friends]
friends_lcase = []
for f in friends:
friends_lcase.append(f.lower())
# present_friends = [
# name.title() for name in guests if name.lower() in friends_lcase
# ]
present_friends = []
for name in guests:
if name.lower() in friends_lcase:
present_friends.append(name.title())
print(present_friends)
祝你好运!
推荐阅读
- haskell - Applicative 中的纯定义问题
- asp.net-core - 如何在从右到左的文化本地化 ASP.Net 核心 2.2 应用程序中启用 RTL 模式?
- c# - 概率论 - COINTOSS on SPOJ
- r - 如何在 r 中导入排列好的 .csv 文件
- python - 如何使用我正在使用的代码使球从绘制的矩形上反弹?
- angular - 'Could not resolve module... relative to...' 编译应用程序时出错
- python - 用我自己的操作系统刷新我的旧捕获盒
- java - 似乎无法将 int 转换为字符串并运行我的程序,因此它输出 330
- python-3.x - 内存问题?如何有效地获得所需的输出?
- php - Laravel 5.8 自定义表单请求未按预期工作?