![](/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.