繁体   English   中英

如何在Python中合并嵌套循环的结果

[英]How to combine the result of nested loop in Python

我需要帮助来组合两次迭代的嵌套循环输出。 这是我嵌套的while代码:

iteration=0
while (iteration < 2):
   count = 0
   bit=5
   numbers = []
   while (count < bit):
      Zero = 0
      One = 1

      IV=(random.choice([Zero, One]))
      numbers.append(IV)
      count= count + 1
   print ('List of bit:', numbers)
   iteration=iteration + 1
   print ("End of iteration",iteration)

结果如下:

List of bit: [1, 0, 1, 1, 0]
End of iteration 1
List of bit: [1, 0, 0, 1, 1]
End of iteration 2

但是,我想结合循环的结果。 据推测,结果可能会产生如下所示:

Combination of bit:[1, 0, 1, 1, 0 ,1 , 0, 0, 1, 1]

希望有人可以帮助我做到这一点。 非常感谢。

绝对应该重组此代码,但这是解决方案。

from itertools import chain

# list for appending results
combined = []    

iteration=0
while (iteration < 2):
    count = 0
    bit=5
    numbers = []
    while (count < bit):
        Zero = 0
        One = 1

        IV=(random.choice([Zero, One]))
        numbers.append(IV)
        count= count + 1
    print ('List of bit:', numbers)
    iteration=iteration + 1
    print ("End of iteration",iteration)

    # append the result
    combined.append(numbers)

# print the combined list
print(list(chain.from_iterable(combined)))

输出量

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

只需在循环外初始化numbers ,而不是在每次迭代时都将其清除,这样您的结果就可以继续附加到numbers

iteration=0
numbers = []
while (iteration < 2):
   count = 0
   bit=5
   while (count < bit):
      Zero = 0
      One = 1

      IV=(random.choice([Zero, One]))
      numbers.append(IV)
      count= count + 1
   print ('List of bit:', numbers)
   iteration=iteration + 1
   print ("End of iteration",iteration)

鉴于该代码仅创建了一个包含10个随机二进制值的列表,因此该代码似乎极其复杂。 您可以通过以下方法获得相同的效果:

>>> import random
>>> [random.choice([0,1]) for _ in range(10)]
[0, 0, 0, 0, 1, 0, 1, 0, 1, 1]

但是,从代码的角度来看,每次迭代产生的值列表在下一次迭代的开始被行numbers = []丢弃。

可以将其移动到初始while语句之前,也可以在while语句之外创建一个单独的列表,并将每个迭代附加到该列表中。

后一种方法(只需对代码进行最少的更改)将如下所示:

iteration=0
all_numbers = [] # List to hold complete set of results

while (iteration < 2):
   count = 0
   bit=5
   numbers = []
   while (count < bit):
      Zero = 0
      One = 1

      IV=(random.choice([Zero, One]))
      numbers.append(IV)
      count= count + 1
   print ('List of bit:', numbers)
   iteration=iteration + 1
   print ("End of iteration",iteration)
   all_numbers.extend(numbers)  # Add the iteration to the complete list

print ('Complete list', all_numbers) # Show the aggregate result

您的numbers变量正在外部循环中重新初始化。

其他答案已经指出了错误的出处,但对于这样一个简单的事情,实际上这是太多的代码。 pythonic方式是一种更简单,更易读的代码:

numbers =  [random.randint(0,1) for i in range(10)]

暂无
暂无

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

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