【问题标题】:Why sorting is not working here?Python 3为什么排序在这里不起作用?Python 3
【发布时间】:2018-03-09 13:01:44
【问题描述】:

谁能告诉我为什么排序在这里不起作用?

    b = input()
    list1  = input().split()
    c = input() 
    list2 = input().split()
    set1 = set(list1)
    set2 = set(list2)
    list3 = list(set1.union(set2) - set1.intersection(set2))
    sorted(list3)
    print(list3)

输入格式:

4

2 4 5 9

4

2 4 11 12

【问题讨论】:

  • 请添加预期的输出 - 你想达到什么目的?
  • 请注意:set1.union(set2) - set1.intersection(set2)可以写成set1.symmetric_difference(set2)...

标签: python-3.x


【解决方案1】:

sorted 没有就地排序。使用

list4 = sorted(list3) 

然后打印出来。见 f.e.这里:https://www.programiz.com/python-programming/methods/built-in/sorted

从 sorted() 返回值 sorted() 方法从给定的可迭代对象中返回一个排序列表。

【讨论】:

    【解决方案2】:

    sorted(list3) 返回一个新列表。

    把它赋值给一个变量

    list3 = sorted(list3)
    

    或使用sort 方法就地更改列表。

    list3.sort()
    

    有关 Python 排序的更多信息,请查看 Python 官方文档中的 Sorting HOW TO

    【讨论】:

    • 那也不行,输出仍然是 ['11', '12', '5', '9']!
    • @Nexus 因为你想先把它们变成整数,不是吗?字符串的排序是正确的...
    • @Nexus 这些是排序的字符串。如果您希望它们是整数,则预先将它们设为整数:list3 = [int(x) for x in list3] 否则,您可以使用键函数对它们进行排序,就像它们是 ints 一样。 list3.sort(key=int)
    • @Nexus:看,你没有很好地解释你有字符串值。然后使用sorted(list3, key=int)
    • 是的!这就解释了!我怎么错过了这个傻点! :( 谢谢@JonClements
    猜你喜欢
    • 2017-05-03
    • 2015-12-05
    • 2013-05-16
    • 2019-02-10
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多