[英]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.