【问题标题】:Python sort multiple lists, then print out same elements firstPython对多个列表进行排序,然后首先打印出相同的元素
【发布时间】:2017-08-27 11:25:37
【问题描述】:

我有三个包含不同元素的列表,但是其中一些是相同的元素。这些相同的元素应该以相同的顺序排列。这是我的代码:

导入迭代工具 a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] b = [0, 2, 4, 6, 8, 10, 12, 14] c = [0, 4, 8, 12, 16] 对于 itertools.zip_longest(a, b, c) 中的 x、y、z: 打印(x,y,z)

当我运行它时,打印出来是这样的:

0 0 0 1 2 4 2 4 8 3 6 12 4 8 16 5 10 无 6 12 无 7 14 无 8 无 无 9 无 无

但我更喜欢他们变成这样:

0 0 0 4 4 4 8 8 8 无 12 12 2 2 无 6 6 无 1 10 16 3 14 无 5 无 无 7 无 无 9 无 无


编辑:这些相同的元素应该在顶部,其中 3 个放在一起。如果 3 个元素中有 2 个相同的元素,我希望它们像:

无 12 12

正如我在上面的示例中指出的那样。如果某些特定行上的元素不同,那没关系,保持原样(参见示例:1 10 16)。 总结一下;我首先需要在特定行上使用相同的 3 个元素。另一个理想的小例子:

a = [2, 1, 3, 5] b = [1, 2] c = [2, 3, 4]

我们的小例子应该变成这样:

2 2 2 3 无 3 1 1 无 5 无 4

【问题讨论】:

  • 我完全不理解您的示例输出。为什么中间一栏现在全是无? 15 去哪儿了?
  • 显然我在写它们时犯了一个错误。用第三个替换第二个
  • 如果问题有问题,edit它。你还没有解释 15 去了哪里。如果您需要帮助,请更清楚地解释您的问题。
  • 我刚刚编辑了问题并尝试对其进行简化。感谢您的关注@AlexHall

标签: python python-3.x


【解决方案1】:
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [0, 2, 4, 6, 8, 10, 12, 14]
c = [0, 4, 8, 12, 16]

max_len = max(len(a),len(b),len(c))
print max_len

while not len(a)==int(max_len):
    a.append(0)


while not len(b)==int(max_len):
    b.append(0)

while not len(c)==int(max_len):
    c.append(0)

print a
print b
print c


d = [max(item) for item in zip(a,b,c)]

m = []
for item in d:
    if item in a:
        val1 = item
        a.remove(item)
    else: 
        val1 = None
    if item in b:
        val2 = item
        b.remove(item)
    else:
        val2 = None
    if item in c:
        val3 = item
        c.remove(item)
    else:
        val3 = None

    m.append((val1,val2,val3))

print m 

输出:

10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8, 10, 12, 14, 0, 0]
[0, 4, 8, 12, 16, 0, 0, 0, 0, 0]
[(0, 0, 0), (4, 4, 4), (8, 8, 8), (None, 12, 12), (None, None, 16), (None, 10, None), (None, None, None), (None, 14, None), (None, None, None), (9, None, None)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-17
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 2014-09-22
    • 2013-02-10
    相关资源
    最近更新 更多