我的代码将输出作为列表
def extractKeywords():
<code>
return list
list = []
data = extractKeywords()
for x in range(0,5):
get = data[0][x]
list.append(get)
print list12
输出列表是
['LION', 'tv', 'TIGER', 'keyboard', 'cd-writer','ELEPHANT']
如何将此列表分类为两组,如(预期输出)
Animals = ['LION', 'TIGER', 'ELEPHANT']
Electronics = ['tv', 'keyboard', 'cd-writer']
所有动物都在Capital letter
,电子设备在small letters
答案 0 :(得分:2)
此解决方案使用itertools.groupby来避免遍历列表两次。
>>> from itertools import groupby
>>> data = ['LION', 'tv', 'TIGER', 'keyboard', 'cd-writer','ELEPHANT']
>>> # upper case letters have lower `ord` values than lower case letters
>>> sort_by_case = sorted(data, key=lambda word: ord(word[0]))
>>> sort_by_case
['ELEPHANT', 'LION', 'TIGER', 'cd-writer', 'keyboard', 'tv']
>>> # group the words according to whether their first letter is upper case or not
>>> group_by_case = groupby(sort_by_case, lambda word: word[0].isupper())
>>> # use tuple unpacking to assign the two groups to appropriate variables
>>> upper_case, lower_case = [list(g) for (k, g) in group_by_case]
>>> upper_case
['ELEPHANT', 'LION', 'TIGER']
>>> lower_case
['cd-writer', 'keyboard', 'tv']
答案 1 :(得分:1)
mylist = ['LION', 'tv', 'TIGER', 'keyboard', 'cd-writer','ELEPHANT']
[word for word in mylist if word==word.lower()]
答案 2 :(得分:1)
这是一种可能的解决方案
>>> from itertools import tee
>>>
>>> def splitOnCondition(lst, condition):
... l1, l2 = tee((condition(i), i) for i in lst)
... return [i for c, i in l1 if c], [i for c, i in l2 if not c]
...
>>> splitOnCondition(['LION', 'tv', 'TIGER', 'keyboard',
... 'cd-writer','ELEPHANT'], lambda x: x==x.lower())
(['tv', 'keyboard', 'cd-writer'], ['LION', 'TIGER', 'ELEPHANT'])