[英]How do I organize lower and upper case words in Python?
Here is the code I have. 这是我的代码。
All I need to do is make sure the list is organized with upper case words first and lower case words second. 我需要做的就是确保列表的开头是大写单词,其次是小写单词。 I looked around but no luck with .sort
or .sorted
command. 我环顾四周,但.sort
或.sorted
命令没有运气。
string = input("Please type in a string? ")
words = string.strip().split()
for word in words:
print(word)
string = raw_input("Please type in a string? ")
words = string.strip().split()
words.sort()
As to how to separate upper and lower case words into separate columns: 关于如何将大写和小写单词分成单独的列:
string = raw_input("Please type in a string? ")
words = string.split()
column1 = []
column2 = []
for word in words:
if word.islower():
column1.append(word)
else
column2.append(word)
The .islower()
function evaluates to true if all the letters are lower case. 如果所有字母均为小写,则.islower()
函数的计算结果为true。 If this doesn't work for your problem's definition of upper and lower case, look into the .isupper() and .istitle() methods here . 如果这不适合您的问题的定义大小写一起工作,期待进入.isupper()和.istitle()方法在这里 。
The sorted()
function should sort items alphabetically taking caps into account. sorted()
函数应按字母顺序对项目进行排序,并考虑到上限。
>>> string = "Don't touch that, Zaphod Beeblebox!"
>>> words = string.split()
>>> print( sorted(words) )
['Beeblebox!', "Don't", 'Zaphod', 'that,', 'touch']
But if for some reason sorted()
ignored caps, then you could do it manually with a sort of list comprehension if you wanted: 但是,如果出于某种原因, sorted()
忽略了大写字母,那么您可以通过某种列表理解手动进行操作:
words = sorted([i for i in words if i[0].isupper()]) + sorted([i for i in words if i[0].islower()])
This creates two separate lists, the first with capitalized words and the second without, then sorts both individually and conjoins them to give the same result. 这将创建两个单独的列表,第一个使用大写单词,第二个不使用大写单词,然后分别对它们进行排序并将它们结合在一起以得到相同的结果。
But in the end you should definitely just use sorted()
; 但是最后,您绝对应该只使用sorted()
; it's much more efficient and concise. 它更加高效和简洁。
EDIT: Sorry, I might have miss-interpreted your question; 编辑:对不起,我可能错过了你的问题的解释; if you want to organize just Caps and not without sorting alphabetically, then this works: 如果您只想组织大写字母而不是不按字母顺序排序,那么可以这样做:
>>> string = "ONE TWO one THREE two three FOUR"
>>> words = string.split()
>>> l = []
>>> print [i for i in [i if i[0].isupper() else l.append(i) for i in words] if i!=None]+l
['ONE', 'TWO', 'THREE', 'FOUR', 'one', 'two', 'three']
I can't find a method that's more efficient then that, so there you go. 我找不到比这更有效的方法,所以就去了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.