如何迭代多个子列表和添加两个元素在一行从子列表到列表?



我有这些基于书籍类型的子列表:

sci_fi = ["Dune", "Fahrenhefgvit 451", "Ender's Game", "Hypterion", "The Foundation Vol.3","The Foundation Vol.2","The Foundation Vol.1","1984"]
fantasy = ["The Wise Man's Fear", "A Clash of Kings", "Malazan Book of the Fallen","The Name of the Wind","Lord of the Rings","A Game of Thrones"]
crime_fiction = ["Murder on the Orient Express","The Cartel","The Girl with the Dragon Tattoo","The Cuckoo's Calling","The Godfather"]
comics = ["The Avengers Vol.3","Spiderman vol.16", "Ghost Rider vol.2", "Spiderman vol.15","John Constantine vol.5", "Batman vol.13","Green Arrow vol.1"]

现在,我要创建一个包含这些书的列表,该列表将按照这些书将被阅读的顺序,基于以下标准:

  1. 我们不想连续读两本相同类型的书(如果可以避免的话)。
  2. 除漫画外,我们希望连续读取2个。

这两个列表的大小不同,因此这些书将被添加,直到列表被迭代为止。当一种类型的书售完时,可以推荐另一种类型的书。

一个可能的输出示例是:

['Dune', 'Murder on the Orient Express', "The Wise Man's Fear", 'The Avengers Vol.3',"Spiderman vol.16", 'Fahrenhefgvit 451', 'The Cartel', 'A Clash of Kings', "Ghost Rider vol.2", "Spiderman vol.15", "Ender's Game", 'The Girl with the Dragon Tattoo', 'Malazan Book of the Fallen', 'Hypterion', "The Cuckoo's Calling", 'The Name of the Wind', "John Constantine vol.5", "Batman vol.13", 'The Foundation Vol.3', 'The Godfather', 'Lord of the Rings', 'Green Arrow vol.1', 'The Foundation Vol.2', 'A Game of Thrones', 'The Foundation Vol.1', '1984']

我将您的数据更改为示例数据,以使其更具可读性。我不知道这是不是一个非常有效的方法,但它的工作方式你想(IIUC)。

基本上你洗牌你的列表,所以你有随机的顺序,然后循环通过它与你的规则。

import random
import itertools
sci = ['A', 'B', 'C']
fan = ['D', 'E', 'F', 'G', 'H']
comics = ['I', 'J', 'K', 'L', 'M', 'N', 'O']
rndm_sci = random.sample(sci, len(sci))
rndm_fan = random.sample(fan, len(fan))
rndm_com = random.sample(comics, len(comics))
print('rndm_sci: ', rndm_sci)
print('rndm_fan: ', rndm_fan)
print('rndm_com: ', rndm_com)
result=[]
for sci,fan,com in itertools.zip_longest(rndm_sci,rndm_fan,itertools.zip_longest(rndm_com[::2], rndm_com[1::2])):
if com is not None:
result.extend([sci, fan, *com])
else:
result.extend([sci, fan])
result = list(filter(None, result))
print('nresult: ', result)

输出:

rndm_sci:  ['A', 'B', 'C']
rndm_fan:  ['F', 'G', 'H', 'E', 'D']
rndm_com:  ['M', 'J', 'K', 'L', 'N', 'I', 'O']
result:  ['A', 'F', 'M', 'J', 'B', 'G', 'K', 'L', 'C', 'H', 'N', 'I', 'E', 'O', 'D']

相关内容

最新更新