繁体   English   中英

Python来自同一代码的不同结果

[英]Python different results from same code

一件非常奇怪的事情发生了。 我试图在2D数组的“比较1”列中回答该问题, 并删除重复的Python,然后做出以下回答(由于该问题的一些现有答案非常紧凑和有效,所以我没有发布),但这是代码我做了:

array = [['abc',2,3,],
        ['abc',2,3],
        ['bb',5,5],
        ['bb',4,6],
        ['sa',3,5],
        ['tt',2,1]]

temp = []
temp2 = []

for item in array:
    temp.append(item[0])

temp2 = list(set(temp))

x = 0
for item in temp2:
    x = 0
    for i in temp:
        if item == i:
            x+=1
        if x >= 2:
            while i in temp:
                temp.remove(i)

for u in array:
    for item in array:
        if item[0] not in temp:
            array.remove(item)

print(array)

该代码应该可以正常工作,并执行给定链接所要求的请求。 但是我得到两对结果:

[['sa', 3, 5], ['tt', 2, 1]]

[['bb', 4, 6], ['tt', 2, 1]]

为什么在运行时相同的东西,相同的编译器,相同的操作系统上的相同代码会产生两个不同的答案? 注意:结果不会交替出现。 在上面列出的两个可能的输出之间,它是随机的。

在Python中,集合没有任何特定的顺序,即实现可以自由选择任何顺序,因此对于每个程序运行,它可能会有所不同。

您将在此处转换为集合:

temp2 = list(set(temp))

订购结果应该给您一致(但可能不正确)的结果:

temp2 = sorted(set(temp))

我的结果为array

排序方式:

temp2 = sorted(set(temp))

array看起来像这样:

[['bb', 4, 6], ['tt', 2, 1]]

反转:

temp2 = sorted(set(temp), reverse=True)

array看起来像这样:

[['sa', 3, 5], ['tt', 2, 1]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM