我试图以一种特定的方式排列字符串的单词:在我的代码下面的输出是“MNWdeorwy”,但我希望它是“deMNorWwy” (所以我需要保持字母顺序,尽管是上层o lowercases)你能帮我理解我错在哪里,为什么? 谢谢
wrd = "MyNewWord" def order_word(s): if s == "": return "Invalid String!" else: c = sorted(s) d = ''.join(sorted(c)) return d print order_word(wrd)我想确切地说我的问题与以下不同: 如何在Python中按字母顺序排列字符串中的字母 :实际上,链接中给出的答案没有考虑字符串中上下字符串之间的区别。
I am trying to order the words of a string in a particular way: In my code below the output is "MNWdeorwy" but i would like it to be "deMNorWwy" (so i need to keep the letters ordered despite being upper o lowercases) Could you please help me to understand where I am wrong and why? Thank you
wrd = "MyNewWord" def order_word(s): if s == "": return "Invalid String!" else: c = sorted(s) d = ''.join(sorted(c)) return d print order_word(wrd)I would like to precise that my question is different from the following: How to sort the letters in a string alphabetically in Python : in fact, the answers given in the link does not consider the difference between upper and lowercases in a string.
最满意答案
sorted()根据每个字符的序数排序。 大写字母的序号低于全部小写字母。 如果你想要不同的行为,你需要定义你自己的密钥:
c = sorted(s, key=lambda c: (c.lower(), c.islower()))这样, c将按('c', 1)排序, C按('c', 0)排序。 两者都出现在('d', ...)或('e', ...)等之前,但大写字母c比小写字母c更早(更低)。
顺便说一句,你不应该说d = "".join(sorted(c))因为c已经被排序。 只要做d = "".join(c)
sorted() sorts based off of the ordinal of each character. Capital letters have ordinals that are lower than all lowercase letters. If you want different behavior, you'll need to define your own key:
c = sorted(s, key=lambda c: (c.lower(), c.islower()))That way, c would be sorted by ('c', 1) and C is sorted by ('c', 0). Both come before ('d', ...) or ('e', ...) etc., but the capital C is earlier (lower) than the lowercase c.
By the way, you shouldn't say d = "".join(sorted(c)) because c has already been sorted. Just do d = "".join(c)
更多推荐
发布评论