如何根据单词的大小写分割(单词)列表。首选使用单个for循环。
输入字符串:
"Capitalized words Get Listed first"
预期结果:
这应该分成两个单独的列表upper
和lower
,分别包含大写单词和小写单词。
例如: upper = [" Capitalized"," Get","已列出"] lower = [" words"," first"]
必须使用这两个列表和一个for循环显示最终输出:
显示中的预期最终输出:
Capitalized
Get
Listed
words
first
答案 0 :(得分:2)
将句子分成单词,然后排序。大写字母将在小写字母之前排序。
l = "Capitalized words Get Listed first"
sortedList = sorted(l.split())
lowerList = []
upperList = []
for word in sortedList:
if word.istitle():
upperList.append(word)
else:
lowerList.append(word)
upperList
['Capitalized', 'Get', 'Listed']
lowerList
['first', 'words']
答案 1 :(得分:0)
也许有点乱,但它有效。它使用@ Cyber的答案,然后更进一步了解额外的细节。
l = "Capitalized words Get Listed first"
sorted_list = sorted(l.split())
lowercase = []
capitalized = []
for word in sorted_list:
if word.capitalize() == word:
capitalized.append(word)
else:
lowercase.append(word)
for word in sorted_list:
print(word)
答案 2 :(得分:0)
这是另一种方式:
import re
import itertools
user_input = "Capitalized Get Listed words first"
splitwords = re.findall(r'''([A-Z][a-z]*)|([a-z]+)''', user_input)
words = [sorted([upper for upper,lower in splitwords if upper]),
sorted([lower for upper,lower in splitwords if lower])]
# this is equivalent to:
# caps, lower = zip(*splitwords)
# words = [sorted(filter(None, caps)), sorted(filter(None, lower))]
# YMMV
for word in itertools.chain(*words):
print(word)
## OUTPUT ##:
Capitalized
Get
Listed
first
words
虽然简单地拆分并找到第一个小写字出现的索引可能更简洁。
user_input = "Capitalized Get Listed words first"
sorted_input = sorted(user_input.split())
for idx, word in enumerate(sorted_input):
if word.islower():
capitalized = sorted_input[:idx]
lowercase = sorted_input[idx:]
words = capitalized + lowercase # concat lists
for word in words:
print(word)
答案 3 :(得分:0)
这些方法不会混淆输出的顺序。
输入
text_array = "Capitalized Words Get Listed first".split()
使用单个for循环:(不使用已排序,因此不会混淆顺序)
upper = []
lower = []
for word in text_array:
if word.istitle():
upper.append(word)
else:
lower.append(word)
使用单个列表理解:
lower = list(text_array)
upper = [ lower.pop(lower.index(word)) for word in text_array if word.istitle() ]
使用两个单独的列表结构:
upper = [ word for word in text_array if word.istitle() ]
lower = [ word for word in text_array if not word.istitle() ]
使用嵌套列表结构:
lower = []
upper = [ word for word in [ word if word.istitle() else lower.append(word) for word in text_array ] if word is not None ]
使用两个过滤器
upper = filter(lambda word : word.istitle(), text_array)
lower = filter(lambda word : not word.istitle(), text_array)
使用单一过滤器:
lower = []
upper = filter(lambda word : True if word.istitle() else bool(lower.append(word)), text_array)
使用单个for循环打印输出:
for word in upper + lower :
print word