Если n-й элемент списка проходит условие, как выбрать n-й элемент другого списка? - PullRequest
0 голосов
/ 31 марта 2020

Если n-й элемент pair_length проходит условие, то я хочу записать в выходной файл n-й элемент x_cords, y_cords и pair_num. Например, если 3-й элемент списка pair_length проходит условие length <= average_pair_length():, то я хочу выбрать 3-й элемент списков x_cords, y_cords и pair_num, чтобы я мог записать их в вывод файл. Я попытался использовать функцию 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

1 Ответ

1 голос
/ 31 марта 2020

Используйте index, чтобы определить, какой элемент находится в массиве

for index, length in enumerate(pair_length): # index tells you which element it is
    if length <= average_pair_length():
        x, y, pair_num = x_cords[index], y_cords[index], pair_nums[index]
        print(x, y, pair_num) 
        # Do what you want to do with the matching x, y, and pair_num here      
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...