Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.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_Grouping - Fatal编程技术网

Python 如何更改列表中项目的分组?

Python 如何更改列表中项目的分组?,python,list,grouping,Python,List,Grouping,如果我有这样一个列表: x = [0,1,2,3,4,5,6,7,8,9] x = [01,23,45,67,89] 如何将此列表转换为以下内容: x = [0,1,2,3,4,5,6,7,8,9] x = [01,23,45,67,89] 我该怎么做 我知道内置的zip功能, 但是我不想要元组,我想要2个数字组合成1。你可以试试这个: x = [0,1,2,3,4,5,6,7,8,9] x = map(str, x) new_list = map(int, [x[i]+x[i+1]

如果我有这样一个列表:

x = [0,1,2,3,4,5,6,7,8,9]
x = [01,23,45,67,89]
如何将此列表转换为以下内容:

x = [0,1,2,3,4,5,6,7,8,9]
x = [01,23,45,67,89]
我该怎么做

我知道内置的
zip
功能, 但是我不想要元组,我想要2个数字组合成1。

你可以试试这个:

x = [0,1,2,3,4,5,6,7,8,9]

x = map(str, x)

new_list = map(int, [x[i]+x[i+1] for i in range(0, len(x)-1, 2)])

使用zip和列表理解,假设数据类型从整数列表变为字符串列表:

In [1]: x = [0,1,2,3,4,5,6,7,8,9]

In [2]: pairs = zip(x[::2], x[1::2])

In [3]: pairs
Out[3]: [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]

In [4]: [str(fst) + str(snd) for fst, snd in pairs] 
Out[4]: ['01', '23', '45', '67', '89']

这更容易理解,并且是一行:

 # l = list of string of items in list u with index(i) and index(i+1) and i increments by 2
 l = [ str( u[i]) + str( u[i+1]) for i in range( 0, len(u), 2)]

修改的
x
列表包含
str
对象或
int
s?01在Python中不是有效的整数表示形式。。。你是说组合整数的函数应该返回字符串吗?还是您的输入实际上是字符串?谢谢您的快速回复!我要试试看!请注意,在Python3中,map返回一个生成器对象而不是列表,因此您必须执行
x=list(map(str,x))
x=[str(i)for i in x]
。我正在使用Python3,所以我必须尝试一下。感谢Rawing不用将两个数字转换成字符串并将结果转换成整数,为什么不用
x[i]*10+x[i+1]
?当然,在这两种情况下,
01
将显示为
1
…我输入了您的代码,当我尝试
print()
时,出于某种原因,它返回一个十六进制内存位置:
考虑到guido想要摆脱map,并且映射到列表的函数没有太大,这可能是更好的答案,也可能更快