在Python中基于单位,十位,百位数对列表进行排序

时间:2015-11-20 07:35:23

标签: python list python-2.7 sorting

假设我有一个列表,我想按以下模式对数字进行排序:

A = [3, 30, 34, 256, 5, 9]

首先按单位数字排序,如果单位数字相同,我们将比较tens place然后hundred place。如果按此规则对A进行排序,则:

A = [9, 5, 34, 3, 30, 256]

9 is the highest digit at Unit place 
5 is second highest
3, 34, 30 since unit digit is same here, we will compare tens place so 34 will come first here, then 3 and 30.
256 will come last since its unit place digit is 2 which is the lowest.

Suppose B = [100, 10, 1]
then after sorting B = [1, 10, 100]

有人可以分享一些Pythonic方法来解决这个问题吗?

我已尝试sorted(nums, key=lambda x: int(x[0]), reverse=True),但在这里我如何考虑tenth place digit

更新:在排序A = [1, 100, 10]之后,假设A = [1, 10, 100]有一点丢失。在示例中,我在排序A = [3, 30, 34, 256, 5, 9]后给了A = [9, 5, 34, 3, 30, 256]

  

总体逻辑是我想加入所有数字并创建一个最大的数字   号。

4 个答案:

答案 0 :(得分:4)

我认为你只想把str作为关键:

In [11]: sorted(A, key=str, reverse=True)
Out[11]: [9, 5, 34, 30, 3, 256]

最初,我读到了你想要反转数字的问题:

In [12]: sorted(A, key=lambda x: str(x)[::-1])
Out[12]: [30, 3, 34, 5, 256, 9]

答案 1 :(得分:2)

以下代码回答了更新后的问题:“以连续排序的数字排序的方式进行排序”。 这个想法是,如果最高有效数字是相同的并且长度不同,则较长的数字比较短的数字“更大”,如果在较长的数字中(较短的数字长度+ 1)数字大于或等于最高有效数字。例如:30< 3,32< 3,35> 3,10< 1,3003> 3,3001< 3,345> 34,342< 34。

>>> def f(x, y):
...     if x == y:
...         return 0
...     xs = str(x)
...     ys = str(y)
...     for i in range(min(len(xs), len(ys))):
...         if xs[i] > ys[i]:
...             return 1
...         elif xs[i] < ys[i]:
...             return -1
...     if len(xs) > len(ys):
...         return 1 if xs[0] <= xs[len(ys)] else -1
...     return -1 if ys[0] <= ys[len(xs)] else 1
...
>>> A = [3, 30, 34, 256, 5, 9]
>>> B = [100,10,1]
>>> sorted(A, cmp=f, reverse=True)
[9, 5, 34, 3, 30, 256]
>>> sorted(B, cmp=f, reverse=True)
[1, 10, 100]

答案 2 :(得分:1)

哦,你真的想要一个数字为文本的字符串排序。好吧,如果你想要单位 - &gt;数十 - &gt;您描述的数百种,这样做:

# Repeatedly modulo 10 to get the rightmost digit
# (units, then tens, then hundreds) until the 
# digit where the two numbers differ. Compare those two digits.
>>> def f(x, y):
...     xr = x % 10
...     yr = y % 10
...     while x and y and xr == yr:
...         x, xr = divmod(x, 10)
...         y, yr = divmod(y, 10)
...     return cmp(xr, yr)
... 
>>> A = [3, 30, 34, 256, 5, 9]
>>> sorted(A, cmp=f)
[30, 3, 34, 5, 256, 9]

它不是作为你的示例输出排序,而是按单位排序 - 0,3,4,5,6,9。如果它有任何单位相同的地方,则排序数十,等等。 / p>

>>> A = [3, 30, 34, 266, 256, 5, 9]
>>> sorted(A, cmp=f)
[30, 3, 34, 5, 256, 266, 9]

答案 3 :(得分:0)

这是与之前发布的其他答案不同的版本:

import itertools

def produce_list(A):
   At = [str(x) for x in A]  # convert the items to str so we can join them
   result = 0
   for i in itertools.permutations(At):  # go through all permutations
      temp = int(''.join(i))
      if result < temp:   # find the biggest value of the combined numbers
          result = temp
          result_list = list(i)

   return [int(x) for x in result_list]  # return the list of ints

print produce_list([3, 30, 34, 256, 5, 9])
print produce_list([100, 1, 10])

它可能不是很有效(它会经历每一个组合)但它和Pythonic一样。