首页 > 解决方案 > 如何打印连续条件的结果,使它们彼此跟随而不按值排序?

问题描述

我的代码在循环中分配值 1 和 0。在 if 条件中,它只列出值 1 在某些位置的那些。它可以正常工作。

import os
import numpy as np
from itertools import combinations


a=np.array([0, 0, 0, 1, 1, 1, 2, 2, 2])
b=np.array([0, 1, 2, 0, 1, 2, 0, 1, 2])
z1=np.array([1, 1])
z2=np.array([1, 1])
comb_x=np.array([0, 0, 1, 1])
comb_y=np.array([0, 1, 0, 1])
for (j), (k) in zip(a,b):
    #print(j,k)    
    z1[:]=0
    z1[:j]=1
    x12=z1
    z2[:]=0
    z2[:k]=1
    y12=z2  
    #print(x12,y12)
                
    if x12[0]==1 and y12[0]==1:
        print(x12,y12)
    if x12[0]==1 and y12[1]==1:
        print(x12,y12)
    if x12[1]==1 and y12[0]==1:
        print(x12,y12)
    if x12[1]==1 and y12[1]==1:
        print(x12,y12)

问题是它没有列出它们,因为各个条件在迭代中彼此跟随,但它根据值对条件的结果进行排序,而不管曾经出现过哪个条件。

我的输出:

[1 0] [1 0]
[1 0] [1 1]
[1 0] [1 1]
[1 1] [1 0]
[1 1] [1 0]
[1 1] [1 1]
[1 1] [1 1]
[1 1] [1 1]
[1 1] [1 1]

当我逐个运行各个条件时,每个条件的列表如下

if x12[0]==1 and y12[0]==1:
        print(x12,y12)


[1 0] [1 0]
[1 0] [1 1]
[1 1] [1 0]
[1 1] [1 1]

 if x12[0]==1 and y12[1]==1:
        print(x12,y12)

[1 0] [1 1]
[1 1] [1 1]

if x12[1]==1 and y12[0]==1:
        print(x12,y12)
[1 1] [1 0]
[1 1] [1 1]

if x12[1]==1 and y12[1]==1:
        print(x12,y12)

[1 1] [1 1]

即使我一次运行它们,它也应该是这样的。这些是上述相关的个人条件。

所需输出

[1 0] [1 0]
[1 0] [1 1]
[1 1] [1 0]
[1 1] [1 1]
[1 0] [1 1]
[1 1] [1 1]
[1 1] [1 0]
[1 1] [1 1]
[1 1] [1 1]

我还尝试通过 for 循环使其自动化,它也会对其进行排序。

for (h),(n),(r) in zip(comb_x,comb_y,np.arange(0,4)):
        #print(h,n,'iteracia = ',r)
        if x12[h]==1 and y12[n]==1:
            print('pravda',x12,y12)

我不明白为什么它按数字 1 升序排列我。

任何人都可以建议我随着条件的发展而不是解决它们吗?

标签: pythonnumpyfor-loopif-statement

解决方案


您的问题是您随时打印结果,这会使结果混淆。您需要从第一个、第二个、第三个和第四个“if 条件”中保存答案,然后使用嵌套循环打印它们。

import os
import numpy as np
from itertools import combinations

a = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2])
b = np.array([0, 1, 2, 0, 1, 2, 0, 1, 2])
z1 = np.array([1, 1])
z2 = np.array([1, 1])
comb_x = np.array([0, 0, 1, 1])
comb_y = np.array([0, 1, 0, 1])
letsgo = [[],[],[],[]]
for (j), (k) in zip(a, b):
    found = False
    # print(j,k)
    z1[:] = 0
    z1[:j] = 1
    x12 = z1
    z2[:] = 0
    z2[:k] = 1
    y12 = z2
    # print(x12,y12)
    if x12[0] == 1 and y12[0] == 1:
        letsgo[0].append(f'{x12} {y12}')
    if x12[0] == 1 and y12[1] == 1:
        letsgo[1].append(f'{x12} {y12}')
    if x12[1] == 1 and y12[0] == 1:
        letsgo[2].append(f'{x12} {y12}')
    if x12[1] == 1 and y12[1] == 1:
        letsgo[3].append(f'{x12} {y12}')
for list in letsgo:
    for string in list:
        print(string)

推荐阅读