首页 > 解决方案 > 如何从列表理解“转换”两者: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)

标签: pythonpython-3.xfor-loopif-statementlist-comprehension

解决方案


在您在这里提问之前,请花点时间查看一些 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)

祝你好运!


推荐阅读