please don't close this, since i'm a newbie to py3. Help me to "convert" from a list-comprehension with both: for-in & if-in... to "normal" python3 code with loops & conditions:
Why the hassle? Because frankly it will help me understand both of the concepts, since i've just started with py3, it makes me anxious... really badly.
# 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)
Please take your time to check some good book in python like Dive into Python 3 before you ask a question in here.
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)
Good Luck with python !
Nithin Varghese's answer is almost correct.
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()) <--- Change
# 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)
Wolf
wasn't caught as it was not being converted to lowercase before being added to friends_lcase
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.