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

问题描述 投票:0回答:5

我有一个看起来像这样的列表字符串:

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"]

谢谢。

python list sorting uppercase
5个回答
1
投票

以下只是另一种方法。

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

1
投票

[list.sort具有适当的list.sort功能:

key

0
投票

使用您的代码在输出中存在歧义。子字符串:“ DAabcas”和“ AA”都有两个大写字母。我们可以使用第二个因素来打破平局,例如字符串长度(len)。

key

输出

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

0
投票

关于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']

与其他人给出的答案进行比较(在1000000次迭代中使用How to sort using multiple criterias时,结果是相同的[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) ):

timeit

-1
投票

这个问题看起来像是您陷入入门编程课程的问题。好的,您已经对标准代码进行了排序(做得很好),让我们将其提取为函数:

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
© www.soinside.com 2019 - 2024. All rights reserved.