如何按项目字符串中的大写字母数降序对列表进行排序



我有一个列表字符串,如下所示:

strings = ["abc", "a", "AA", "DAabcas", "adesAA", "EFSFDAAAaaa"]

我还有一个已经存在的函数,它遍历列表中的每个元素,并返回每个字符串元素中的大写字母数:

capitals = 0
for i in s:
if i.isupper():
capitals += 1
return capitals

"s"是字符串中的每个项。

我如何使用它来返回按降序排列的列表字符串,首先是大写字母最多的字符串,然后是大写字母最少或没有大写字母的最短单词?

这是我想要的结果:

strings = ["EFSFDAAAaaa","DAabcas","adesAA", "AA", "abc", "a"]

谢谢。

以下只是另一种方法。

strings.sort(key=lambda x:(numCapitals(x), len(x)), reverse=True) # a better way 

list.sort具有适当的key函数:

strings.sort(key=lambda s: (sum(map(str.isupper, s)), len(s)), reverse=True)
# ['EFSFDAAAaaa', 'DAabcas', 'adesAA', 'AA', 'abc', 'a']

使用您的代码时,输出中存在歧义。子字符串:"DAabcas"one_answers"AA"都有两个大写字母。我们可以使用第二个因素来打破联系,比如字符串长度(len(。

def count_capitals(s):
capitals = 0
for i in s:
if i.isupper():
capitals += 1
return capitals
strings = ["abc", "a", "AA", "DAabcas", "adesAA", "EFSFDAAAaaa"]
# Use your function as a [sorting key](https://www.geeksforgeeks.org/sorted-function-python/)
s = sorted(strings, key = lambda x: (count_capitals(x), len(x)), reverse=True)
print(s)

输出

['EFSFDAAAaaa', 'DAabcas', 'adesAA', 'AA', 'abc', 'a']

关于如何使用多个标准进行排序,这里是可以进行的资本数量和长度

def count_capitals(word): # just a shorter way
return len([_for _in word if _.isupper()])
if __name__ == '__main__':
strings = ["abc", "a", "AA", "DAabcas", "adesAA", "EFSFDAAAaaa"]
result = sorted(strings, key=lambda e: (count_capitals(e), len(e)), reverse=True)

# Using another computation and inline it
result = sorted(strings, key=lambda e: (sum(_.isupper() for _ in e), len(e)), reverse=True)

与其他人给出的答案(在1000000次迭代中使用timeit(相比,结果完全相同(https://pastebin.com/T0m3TDp7):

sum([1 for _ in word if _.isupper()]) 0.1112008
len([1 for _ in word if _.isupper()]) 0.11526590000000003
len([_ for _ in word if _.isupper()]) 0.11423499999999998
len([c for c in word if c.isupper()]) 0.12964770000000003
sum(_.isupper() for _ in word)        0.11216479999999997
sum(map(str.isupper, s))              0.112989

这个问题看起来像是你被一个入门编程课程的问题卡住了。好吧,你已经有了排序标准代码(做得很好(,让我们把它提取到一个函数中:

>>> def capcount(s):
...   capitals = 0
...   for i in s:
...     if i.isupper():
...       capitals+=1
...   return capitals
# but in python this can be translated to:
lambda s: sum(1 for c in s if c.isupper())

现在您可以使用此函数作为内置sorted:的关键参数

strings = ["abc", "a", "AA", "DAabcas", "EFSFDAAAaaa", "adesAA"]
sorted(strings, key = lambda s: sum(1 for c in s if c.isupper()))
==> ["abc", "a", "AA", "DAabcas", "adesAA", "EFSFDAAAaaa"]

所以这是按照你想要的相反方式排序的,现在你可以做两件事之一(可能更多(:

# Invert what you have now
min_to_max = sorted(strings, key = lambda s: sum(1 for c in s if c.isupper()))
max_to_min = min_to_max[::-1]
# Or change the sorting function around
# lambda s: sum(-1 for c in s if c.isupper())
max_to_min = sorted(strings, key = lambda s: sum(-1 for c in s if c.isupper()))

最新更新