![](/img/trans.png)
[英]How do I access an object's attribute while iterating through a nested list in Python?
[英]Python: How can I assign names different messages while iterating through a list?
有没有办法在遍历列表时为不同的消息分配名称?
例如:
Names = [Owen, Sophie, Max, Karen, Zedd]
期望输出:
Hello, Owen!
Hello, Sophie!
Hello, Max!
Hello, Karen!
Good morning, Zedd!
这很简单。 只需将您的姓名分成不同的列表,然后在这样的条件下应用。
Names = ['Owen', 'Sophie', 'Max', 'Karen', 'Zedd']
Hello_Names = ['Owen', 'Sophie', 'Max', 'Karen']
Good_Morning_Names = ['Zedd']
for name in Names:
if name in Hello_Names:
print(f'Hello, {name}!')
elif name in Good_Morning_Names:
print(f'Good Morning, {name}!')
如果你想随机分配这个,你可以这样做:
import random
Names = ['Owen', 'Sophie', 'Max', 'Karen', 'Zedd']
for name in Names:
k = random.choice([0, 1])
if k==0:
print(f'Hello, {name}!')
else:
print(f'Good Morning, {name}!')
在 for 循环中使用 if 语句。
Names = ("Owen", "Sophie", "Max", "Karen", "Zedd")
for name in (Names):
if name == "Zedd":
print("Good Morning, "+ name + "!")
else:
print("Hello, "+ name +"!")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.