简体   繁体   English

循环遍历元组列表并解包每个元组的元素

[英]Loop through list of tuples and unpack elements of each tuple

I have this list of two-value tuples我有这个二值元组列表

stake_odds=[(0, 1), (0, 2), (0, 5), (0, 10), (2, 1), (2, 2), **(2, 5)**, (2, 10), (5, 1), (5, 2), (5, 5), (5, 10), (10, 1), (10, 2), (10, 5), (10, 10)]

I have the following function where I want to put the tuple into an object method where it calculates the product (or minus product depending on the instance) of the two numbers in the tuple.我有以下 function 我想将元组放入 object 方法中,在该方法中计算元组中两个数字的乘积(或根据实例减去乘积)。 If the product is positive, I want to append the tuple used to another list, pos_cases .如果产品是肯定的,我想将 append 用于另一个列表pos_cases的元组。

def function():
    pos_cases=[]
    x,y=stake_odds[9]
    b1=bet1.payout(x,y)
    if b1 > 0:
        return b1, "b is greater than zero!"
        pos_cases.append(stake_odds[9])
        print(pos_cases)

print(function())

As you can see below I have to unpack the tuple into two variables before computing.正如您在下面看到的,我必须在计算之前将元组解压缩为两个变量。 I can do it by specifying the element of the list ( stake_odds[9] ), however I am looking for a way to generalize and loop through the list ( stake_odds[i] ) rather than going one by one.我可以通过指定列表的元素( stake_odds[9] )来做到这一点,但是我正在寻找一种方法来概括和遍历列表( stake_odds[i] ),而不是一个一个地进行。

The list in this example would be shortened to the following:此示例中的列表将缩短为以下内容:

pos_cases =[(2, 1), (2, 2), (2, 5), (2, 10), (5, 1), (5, 2), (5, 5), (5, 10), (10, 1), (10, 2), (10, 5), (10, 10)]

How could I do this?我怎么能这样做? The only thing I can think of is some nested for loop like:我唯一能想到的是一些嵌套的for循环,例如:

for i in stake_odds: 
    for x,y in i:
        return(x,y)

But this results in error >TypeError: cannot unpack non-iterable int object> .但这会导致error >TypeError: cannot unpack non-iterable int object>

Doesn't this work?:这不起作用吗?:

def function():
    pos_cases=[]
    for x,y in stake_odds:
        b1=bet1.payout(x,y)
        if b1 > 0:
            return b1, "b is greater than zero!"
            pos_cases.append((x,y))
    return pos_cases

print(function())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM