[英]How do I take the nth element of a list and compare to the last nth elements of the same list
[英]If the nth element of a list passes a condition, how do I select the nth element of another list?
如果pair_length
的第 n 個元素通過一個條件,那么我想將x_cords
、 y_cords
和pair_num
的第 n 個元素寫入輸出文件。 例如,如果pair_length
列表的第三個元素通過條件length <= average_pair_length():
,那么我想選擇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
使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.