我有一些示例代碼如下:import numpy as npimport pandas as pdx = range(1, 12)arr1 = np.random.randint(x)arr2 = np.array(x)arr3 = np.random.randint(x)arr4 = np.random.randint(x)arr5 = np.random.randint(0, 2, 11)dict_df = { 'arr1' : arr1, 'arr2' : arr2, 'arr3' : arr3, 'arr4' : arr4, 'arr5' : arr5}d = pd.DataFrame(dict_df)num_count = 0list_of_num = []for i in d.index: number = d['arr1'][i] for num in d['arr5']: if num == 1: num_count = 1 number = number list_of_num.append(number) elif num == 0: num_count = 0print(list_of_num)我正在嘗試構(gòu)建列表,如果列中的所有列前面arr5都有 -1,則它們都會(huì)附加到列表中。我從中收到的輸出是:[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 6, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 1, 5, 5, 5, 5, 5, 5, 2, 2, 2, 2, 2, 2, 8, 8, 8, 8, 8, 8]代碼的問(wèn)題是我誤用了for循環(huán),這就是為什么列表重復(fù)了這么多次的原因。我怎樣才能更改代碼以使代碼不會(huì)重復(fù)?
如何調(diào)整 for 循環(huán)以便它只打印一次列表?
慕的地8271018
2023-04-11 15:54:05