如果pair_length
的第n个元素通过条件,那么我想将x_cords
,y_cords
和pair_num
的第n个元素写入输出文件。例如,如果pair_length
列表的第3个元素通过条件length <= average_pair_length():
,那么我想选择x_cords
,y_cords
和pair_num
列表的第3个元素,以便可以将它们写入输出文件。我尝试使用filter()函数,但没有返回我想要的。这是我的代码:
pair_length = []
pair_nums = []
x_cords = []
y_cords = []
for line in islice(data, 1, None):
fields = line.split(" ")
pair_num = float(fields[0])
pair_nums.append(pair_num)
x_cord = float(fields[1])
x_cords.append(x_cord)
y_cord = float(fields[2])
y_cords.append(y_cord)
vector_length = sqrt(x_cord**2 + y_cord**2)
pair_length.append(vector_length)
def average_pair_length():
average = mean(pair_length)
return average
index = 0
for index, length in enumerate(pair_length):
if length <= average_pair_length():
#this is where I want to find the nth element of pair_length so I can find the nth elements in the other lists
使用index
确定它在数组中是哪个元素
for index, length in enumerate(pair_length): # index tells you which element it is
if length <= average_pair_length():
pair_nums[index] = new_pair_num # assign the new value here
x_cords[index] = new_x_cord # assign the new value here
y_cords[index] = new_y_cord # assign the value here