如何使用的范围循环通过两个列表在Python迭代?

问题描述 投票:-3回答:3

需要一些帮助,请使用与范围和len循环。两个问题。

说我有一个列表,包括任何“W‘或’L的意思是比赛赢了还是比赛输了,并与代表分的得分(和位置对应于同一游戏)整数第二列表,然后我怎么会写一个函数(不使用压缩功能),这将告诉例如用户“为什么我们有多少场比赛取胜,正是得分3分”?而“多少场比赛没有取胜,我们至少有9分”?

起初,我试图合并这两个名单和位置,即 - 位置0将有类似L4的值。然后,我可以搜索特定的标准,但这个超过特定数量的或大或小点搜索(至少有X点赢)时变得非常棘手。

现在,我通过一个循环,在范围(X))和len思维迭代像我为我。但我很困惑如何做到这一点有两个列表工作,我还是很新的编码和获取语法的窍门。

谢谢您的输入和时间

my code is a disaster....

def score_check(lst1, lst2):
    for 'W' in range(lst1[i] if 3 in lst2[i]):
    .........
    .....
    return result 

def main():
    record = ['L', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'L', 'W', 'W']
    points = [4, 1, 3, 2, 7, 4, 3, 10, 8, 14, 7, 6, 7]

    check = score_check(record, points)
    print(check)

main()

预期成绩:

2 wins with 3 points scored and
2 wins with at least 9 points scored
python list function loops
3个回答
1
投票

所以,我认为最好的办法是使用zip。但是,你不想使用,你可以这样做:

def score_check(lst1, lst2):
    lst_size_1 = len(lst1)
    lst_size_2 = len(lst2)
    if (lst_size_1 !=lst_size_2):
        return

    for i in range(lst_size):
        print (lst1[i])
        print (lst2[i])

祝好运!


0
投票

如果你不能使用zip那么你可以只使用元素的索引。

record = ['L', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'L', 'W', 'W']
points = [4, 1, 3, 2, 7, 4, 3, 10, 8, 14, 7, 6, 7]

combined = [{'points': points[i], 'result': record[i]} for i in range(len(record))]

# this way is cleaner
#combined = [{'points': p, 'result': r} for r, p in zip(record, points)] 

现在combined是包含键/值对在原始列表中的record和点entries词典列表。它假定这两个列表的长度相同,但是这似乎是一个合理的假设,否则你的数据是不是真的有效。 zip会因此耗尽了两个列表中较短时停止无缝地处理这个问题。如果它试图在任一列表访问一个不存在的索引此代码将抛出。

如果你想现在查询这份名单,你可以只使用filter内置函数,并将它传递一个谓词来决定什么是结果,什么不是。

print('matches where score was greater than 3')
for result in filter(lambda r: r['points'] > 3, combined):
    print(result)

这包括一个点值大于3的任何条目,您可以很容易地使<(小于),>=(比大或等于)或==(等于)任何你想要的号码。

您也可以结合的结果参数到什么是对过滤

print('matches where score was less than 5 but won')
for result in filter(lambda r: r['points'] < 5 and r['result'] == 'W', combined):
    print(result)

注意:该过滤器功能总是线性(O(N))。他们总是在所有条目运行。因此,对于较大的结果集的低效和缓慢的。调整它的一种方法是按分数排序列表,并使用二进制搜索(python中bisect模块),以缩小搜索范围。如果您是基于分数搜索这只会产生影响。如果你想在W / L的结果进行搜索,那么你又回到了线性。


0
投票

所以,拉链是不允许的。怎么样列表理解:

def score_check(results, points):
    wins = [points[i] for i, v in enumerate(results) if v == 'W']
    exactly_three = len([win for win in wins if win == 3])
    at_least_nine = len([win for win in wins if win >= 9])

    return (f'{exactly_three} wins with 3 points scored',
            f'{at_least_nine} wins with at least 9 points scored')

record = ['L', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'W', 'L', 'W', 'W']
points = [4, 1, 3, 2, 7, 4, 3, 10, 8, 14, 7, 6, 7]

print(*score_check(record, points), sep='\n')

2 wins with 3 points scored
2 wins with at least 9 points scored

当函数参数是两个列表只有以获得所需的输出文本和条件必须是硬编码的,这是不是功能的最佳使用。

© www.soinside.com 2019 - 2024. All rights reserved.