Python - 列表映射

标签 python dictionary list-comprehension tuples

我有几个列表,我想将它们映射在一起,但我无法完全思考如何去做。

我正在抓取赛马结果的实时提要。如果比赛被放弃,提要仅列出一次类(class)/时间和三匹马及其位置(前三名)或四匹马和空白(即“”)位置。这些是我的列表:

course, time, abandoned, horses, position

列表是有序的。

coursetimeabandoned 都具有完全相同数量的元素(abandoned 是一个 bool 值列表,True 表示种族是弃)。

horses 是(3 * 未放弃比赛的数量)+(4 * 放弃比赛的数量)马的列表。

position 是马的位置列表。如果比赛被放弃,位置将为“”,否则为“1”、“2”、“3”(字符串!)。

示例列表:

没有种族被放弃

course = ["Course A", "Course A", "Course B"] #there were two races at course A
times  = ["00:00", "01:00", "15:00"] #Race 1 at Course A was at 00:00, race 2 at course                   A was at 01:00
horses = ["HorseA 1", "HorseA 2", "HorseA 3", "HorseA 4", "HorseA 5", "HorseA 6", "HorseB 1", "HorseB 2", "HorseB 3"] #There are three horses per race

positions = ["1","2","3","1","2","3","1","2","3"]

因此,在 00:00 的比赛中,在赛道 A 中,“HorseA 1”获得第一名,“HorseA 2”获得第二名,“HorseA 3”获得第三名。

哪里有被遗弃的种族

courses = ["CourseX", "CourseX", "CourseY"]
times   = ["01:00",  "02:00", "01:00"]
abandoned = [False, False, True]
horses = ["X1", "X2", "X3", "X4", "X5", "X6", "Y1", "Y2", "Y3", "Y4"]
positions = ["1","2","3","1","2","3","","","",""]

因此,CourseX 有两场比赛,但 CourseY 的比赛被放弃了。

我最终想要的是像这样的元组列表:

[(A Race Course, 00:00, False, Horsey, 1), (A Race Course, 00:00, False, Horsey 2, 2) ... ]

我不确定我该怎么做,有建议吗?

干杯,

皮特

最佳答案

>>> class s:
    courses = ["CourseX", "CourseX", "CourseY"]
    times   = ["01:00",  "02:00", "01:00"]
    abandoned = [False, False, True]
    horses = ["X1", "X2", "X3", "X4", "X5", "X6", "Y1", "Y2", "Y3", "Y4"]
    positions = ["1","2","3","1","2","3","","","",""]

>>> def races(courses, times, abandoned, horses, positions):
    z = zip(horses, positions)
    for course, time, stopped in zip(courses, times, abandoned):
        for _ in range(4 if stopped else 3):
            horse, pos = next(z)
            yield course, time, stopped, horse, pos


>>> print(*races(s.courses, s.times, s.abandoned, s.horses, s.positions), sep='\n')
('CourseX', '01:00', False, 'X1', '1')
('CourseX', '01:00', False, 'X2', '2')
('CourseX', '01:00', False, 'X3', '3')
('CourseX', '02:00', False, 'X4', '1')
('CourseX', '02:00', False, 'X5', '2')
('CourseX', '02:00', False, 'X6', '3')
('CourseY', '01:00', True, 'Y1', '')
('CourseY', '01:00', True, 'Y2', '')
('CourseY', '01:00', True, 'Y3', '')
('CourseY', '01:00', True, 'Y4', '')

关于Python - 列表映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3970544/

相关文章:

python - 使用推导式创建 Python 字典

python - 如何检查 pandas 数据框是否仅按列包含数值?

C++ STL map 存储和内存使用

Erlang 列表理解,按顺序使用两个列表?

dictionary - Lisp:多维数组逐元素操作

C# 字典,键是字符串,值是计数器。近似算法和线程安全

python - 使用理解和范围创建嵌套

python - 为什么 sklearn 的套索系数不等于线性回归系数?

python - 如何在 Python 3 中复制 Python 2 风格的 len()?

python - 在pyparsing中,如何分配一个 "no match"键值?