[英]One-liner to print two statements in a for-loop in one line
如何在一行中編寫此代碼? 這個概念是你應該:
alexander
,則 output 應該是eeaa X R NLD
這是我到目前為止提出的代碼:
h = []
for i in input() : h.append(i.lower() if (ord(i) - 97) % 2 == 0 else i.upper())
print(*sorted(h, reverse=True))
問題的原始代碼,您應該將其轉換為一行:
input_string = str(input())
array = []
for i in range(len(input_string)):
if (ord(input_string[i]) - 97) % 2 == 0:
array.append(input_string[i])
else:
array.append(input_string[i].upper())
array.sort(reverse=True)
answer = ' '.join(array)
print(answer)
列表理解(我沒有檢查你的代碼,只是重寫它):
h = []
for i in input() : h.append(i.lower() if (ord(i) - 97) % 2 == 0 else i.upper())
print(*sorted(h, reverse=True))
print(*sorted([i.lower() if (ord(i)-97)%2 == 0 else i.upper() for i in input() ], reverse=True))
引用您的問題:
你應該打印字符的原始形式
這不是代碼目前所做的,只是說你知道。
閱讀您已刪除的評論后:
如果您想知道列表理解中的if
和else
:
你可以把它放在你的列表中,但如果這是你的問題(顯然是實際問題),那么我建議使用谷歌,有很多使用它的例子。: if/else in a list comprehension , https:/ /towardsdatascience.com/a-gentle-introduction-to-flow-control-loops-and-list-comprehensions-for-beginners-3dbaabd7cd8a,https://pythonguides.com/python-list-comprehension-using-if-else _ /
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.