[英]Python - arranging words in alphabetical order
程序必須按字母順序打印8個元素中的最后一個名稱。 名稱/單詞可以通過代碼以任何方式輸入。 我想我應該in range()
這里使用列表和in range()
。 我有一個想法是將輸入名稱的第一個/第二個/第三個/ ...字母與前一個字母進行比較,然后將其放在列表的末尾或前一個的前面(取決於比較),然后重復下一個名稱。 最后,程序將打印列表的最后一個成員。
默認情況下,Python的字符串比較是詞法,所以你應該能夠調用max
並遠離它:
In [15]: sentence
Out[15]: ['this', 'is', 'a', 'sentence']
In [16]: max(sentence)
Out[16]: 'this'
當然,如果你想手動執行此操作:
In [16]: sentence
Out[16]: ['this', 'is', 'a', 'sentence']
In [17]: answer = ''
In [18]: for word in sentence:
....: if word > answer:
....: answer = word
....:
In [19]: print answer
this
或者你可以對你的句子排序:
In [20]: sentence
Out[20]: ['this', 'is', 'a', 'sentence']
In [21]: sorted(sentence)[-1]
Out[21]: 'this'
或者,將其排序:
In [25]: sentence
Out[25]: ['this', 'is', 'a', 'sentence']
In [26]: sorted(sentence, reverse=True)[0]
Out[26]: 'this'
但如果你想完全手動(這是如此痛苦):
def compare(s1, s2):
for i,j in zip(s1, s2):
if ord(i)<ord(j):
return -1
elif ord(i)>ord(j):
return 1
if len(s1)<len(s2):
return -1
elif len(s1)>len(s2):
return 1
else return 0
answer = sentence[0]
for word in sentence[1:]:
if compare(answer, word) == -1:
answer = word
# answer now contains the biggest word in your sentence
如果你想讓它與大小寫無關,請務必首先在你的word
上調用str.lower()
:
sentence = [word.lower() for word in sentence] # do this before running any of the above algorithms
使用sort()
方法。
strings = ['c', 'b', 'a']
strings.sort()
print strings
輸出將是,
['a', 'b', 'c']
如果你想要最后一個,你可以使用max()
方法。
如前一個答案中所述,字符串比較默認是詞法,因此可以使用min()
和max()
。 要處理高位和低位的單詞,可以指定key=str.lower
。 例如:
s=['This', 'used', 'to', 'be', 'a', 'Whopping', 'Great', 'sentence']
print min(s), min(s, key=str.lower)
# Great a
print max(s), max(s, key=str.lower)
# used Whopping
如果您混合使用大寫單詞和小寫單詞,則可以執行以下操作:
from string import capwords
words = ['bear', 'Apple', 'Zebra','horse']
words.sort(key = lambda k : k.lower())
answer = words[-1]
結果:
>>> answer
'Zebra'
>>> words
['Apple', 'bear', 'horse', 'Zebra']
這就是我將如何做到這一點。
定義字符串:為了參數,讓我們說字符串已經預定義了。
sentence = "This is the sentence that I need sorted"
使用split()
方法: split()
方法返回sentence
字符串中的“單詞”列表。 我在這里松散地使用術語“單詞”,因為該方法沒有“單詞”的概念,它只是通過解析由空格分隔的字符將sentence
字符串分成列表,並將這些字符作為離散項輸出到列表中。 此列表尚未按字母順序排列。
split_sentence = sentence.split()
使用sorted
函數: sorted函數返回split_sentence
列表的按字母順序排列的版本。
sorted_sentence = sorted(split_sentence)
打印列表中的最后一個元素:
print(sorted_sentence[-1])
在python中,方法sort()按字母順序對所有字符串進行排序,以便您可以使用該函數。
您可以列出所有單詞,然后:
listName.sort()
這將產生按字母順序排序的列表。
只需使用以下內容:
max(sentence.lower().split())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.