Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
按特定顺序/顺序合并python列表_Python_List_Python 3.x_Merge_Sequence - Fatal编程技术网

按特定顺序/顺序合并python列表

按特定顺序/顺序合并python列表,python,list,python-3.x,merge,sequence,Python,List,Python 3.x,Merge,Sequence,我试着列出两个类似的列表: list_numbers = [1,2,3,4,5,6,7,8,9,10,11,12] list_letters= ["onetothree", "fourtosix", "seventonine", "tentotwelve"] 进入 这只是描述我的问题的一种方式。我需要对列表号和列表字母中的所有元素执行此操作。列表编号中的一个或多个元素始终可以除以列表字母中的元素数量,因此无需担心“扭曲数据” 搜索了整整三个小时,尝试了许多不同类型的“for”和“while”循

我试着列出两个类似的列表:

list_numbers = [1,2,3,4,5,6,7,8,9,10,11,12]
list_letters= ["onetothree", "fourtosix", "seventonine", "tentotwelve"]
进入

这只是描述我的问题的一种方式。我需要对列表号和列表字母中的所有元素执行此操作。列表编号中的一个或多个元素始终可以除以列表字母中的元素数量,因此无需担心“扭曲数据”


搜索了整整三个小时,尝试了许多不同类型的“for”和“while”循环,只得到了python 2.x的问题、糟糕的结果和语法错误,我想我可能应该发布这个问题。

很有技巧,但它可以完成任务

>>> list_numbers = [1,2,3,4,5,6,7,8,9,10,11,12]
>>> list_letters= ["onetothree", "fourtosix", "seventonine", "tentotwelve"]
>>> list(itertools.chain.from_iterable(zip(list_letters, *zip(*[list_numbers[i:i+3] for i in range(0, len(list_numbers), 3)]))))
['onetothree', 1, 2, 3, 'fourtosix', 4, 5, 6, 'seventonine', 7, 8, 9, 'tentotwelve', 10, 11, 12]
或者,更干净的版本:

>>> answer = []
>>> i = 0
>>> for letter in list_letters:
...     answer.append(letter)
...     for j in range(3):
...         answer.append(list_numbers[i+j])
...     i += j+1
... 
>>> answer
['onetothree', 1, 2, 3, 'fourtosix', 4, 5, 6, 'seventonine', 7, 8, 9, 'tentotwelve', 10, 11, 12]
当然,如果您在
列表编号中没有足够多的条目
,您将被烧掉

尝试以下方法:

list_numbers = [1,2,3,4,5,6,7,8,9,10,11,12]
list_letters= ["onetothree", "fourtosix", "seventonine", "tentotwelve"]
list_both=[]
c=1
for n in range(len(list_letters)):
        list_both.append(list_letters[n])
        list_both[c+n:c+n]=list_numbers[c-1:c+2]
        c+=3
print(list_both)

我爱你。另一个令我头疼的问题是,如何让它们(从一个列表中)成为一系列列表,最好是具有唯一名称的列表。例如,['onetothree',1,2,3,'fourtosix',4,5,6,'seventonine',7,8,9,'tentotwelve',10,11,12]到列表1=['onetothree',1,2,3]列表2=['fourtosix',4,5,6]列表名'listx'需要能够无限循环,所以我需要在它们上面有唯一的名称。你知道怎么做吗?我在列表编号中总是有足够多的条目。感谢您提供了简洁的版本。在这里有很多爱:)您可以动态创建具有不同名称的变量(实际上您可以,使用
eval
等,但您不应该这样做)。最简单的方法就是去。如果这不起作用,发布另一个问题,我(或其他人)将提供帮助;]
list_numbers = [1,2,3,4,5,6,7,8,9,10,11,12]
list_letters= ["onetothree", "fourtosix", "seventonine", "tentotwelve"]
list_both=[]
c=1
for n in range(len(list_letters)):
        list_both.append(list_letters[n])
        list_both[c+n:c+n]=list_numbers[c-1:c+2]
        c+=3
print(list_both)