通过在元组列表中查找第二个元素的最小正值来返回第一个元素

发布于 2025-01-12 00:46:57 字数 119 浏览 0 评论 0原文

如何通过查找第二个元素中的最小正数来返回元组列表中的第一个元素?

例如

a_list = [(0,6),(1,2),(2,-2),(3,-5)]

返回 1?

How can I return the first element of in a list of tuples by finding the smallest postive number in the second element?

e.g

a_list = [(0,6),(1,2),(2,-2),(3,-5)]

to return 1?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

箹锭⒈辈孓 2025-01-19 00:46:57

您可以通过将原始列表分成两部分,然后确定第二个列表中的最小正值来实现此目的。然后,您可以通过传递最小值来打印索引,或者在原始列表上使用方括号表示法来返回元组本身。

#Create the list
a_list = [(0,6),(1,2),(2,-2),(3,-5)]

#Split the tuple into two lists
first_element = [i[0] for i in a_list]
second_element = [i[1] for i in a_list]

#Find the smallest positive
smallest = min([i for i in second_element if i > 0])

#Return the index
where_in_list = second_element.index(smallest)

#Method 1
print(where_in_list)

#Method 2
a_list[where_in_list]

方法 1 的输出为 1,方法 2 的输出为 (1, 2)。

You can do this by splitting your original list into two and then determining the smallest positive value in the second list. You can then print the index by passing it your smallest value, or use square bracket notation on your original list to return the tuple itself.

#Create the list
a_list = [(0,6),(1,2),(2,-2),(3,-5)]

#Split the tuple into two lists
first_element = [i[0] for i in a_list]
second_element = [i[1] for i in a_list]

#Find the smallest positive
smallest = min([i for i in second_element if i > 0])

#Return the index
where_in_list = second_element.index(smallest)

#Method 1
print(where_in_list)

#Method 2
a_list[where_in_list]

Output is 1 for Method 1 and (1, 2) for Method 2.

○闲身 2025-01-19 00:46:57

尝试:

a_list = [(0,6),(1,2),(2,-2),(3,-5)]
#Currently set min value to first value for comparison
min = a_list[0][0]
#Loop through tuples in list
for n in range(len(a_list)):
  #If first value is 0, make min the next value for comparison
  if min == 0:
    min = a_list[n + 1][0]
  #To replace min value if the current value in iteration is less than the minimum value
  if a_list[n][0] < min and min != 0:
    min = a_list[n][0]

print(min) #To see minimum value

Try:

a_list = [(0,6),(1,2),(2,-2),(3,-5)]
#Currently set min value to first value for comparison
min = a_list[0][0]
#Loop through tuples in list
for n in range(len(a_list)):
  #If first value is 0, make min the next value for comparison
  if min == 0:
    min = a_list[n + 1][0]
  #To replace min value if the current value in iteration is less than the minimum value
  if a_list[n][0] < min and min != 0:
    min = a_list[n][0]

print(min) #To see minimum value
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文