Cra*_*er0 8 python list range alphabetical
程序必须按字母顺序打印8个元素中的最后一个名称.名称/单词可以通过代码以任何方式输入.我想我应该在in range()这里使用列表.我有一个想法是将输入名称的第一个/第二个/第三个/ ...字母与前一个字母进行比较,然后将其放在列表的末尾或前一个的前面(取决于比较),然后重复下一个名称.最后,程序将打印列表的最后一个成员.
Python的字符串比较默认是词法,所以你应该能够调用max并逃脱:
In [15]: sentence
Out[15]: ['this', 'is', 'a', 'sentence']
In [16]: max(sentence)
Out[16]: 'this'
Run Code Online (Sandbox Code Playgroud)
当然,如果你想手动执行此操作:
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
Run Code Online (Sandbox Code Playgroud)
或者你可以对你的句子排序:
In [20]: sentence
Out[20]: ['this', 'is', 'a', 'sentence']
In [21]: sorted(sentence)[-1]
Out[21]: 'this'
Run Code Online (Sandbox Code Playgroud)
或者,将其排序:
In [25]: sentence
Out[25]: ['this', 'is', 'a', 'sentence']
In [26]: sorted(sentence, reverse=True)[0]
Out[26]: 'this'
Run Code Online (Sandbox Code Playgroud)
但如果你想完全手动(这是如此痛苦):
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
Run Code Online (Sandbox Code Playgroud)
如果您希望这与大写字母无关,请务必首先致电str.lower()您word:
sentence = [word.lower() for word in sentence] # do this before running any of the above algorithms
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59148 次 |
| 最近记录: |