我编写了一个程序,它从excel电子表格中取出行并将它们作为列表返回。我不是要编辑每个创建的列表:
...从
['-1', '3', '4', '5', '3', '7', '2', '4', '0', '8', '12', '23', '4', '0']
为...
['-1', '1:3', '2:4', '3:5', '4:3', '5:7', '6:2', '7:4', '8:0', '9:8', '10:12', '11:23', '12:4', '13:0']
import csv
with open('testingSeta.csv') as csvfile:
reader = csv.reader(csvfile)
line = True
for row in reader:
if line:
line = False
continue
x = row.pop()
row.insert(0,x)
print(row)
答案 0 :(得分:1)
尝试列表理解:
src = ['-1', '3', '4', '5', '3', '7', '2', '4', '0', '8', '12', '23', '4', '0']
src[0:1] + [ str(i+1) + ":" + v for i,v in enumerate(src[1:])]
结果是:
['-1',
'1:3',
'2:4',
'3:5',
'4:3',
'5:7',
'6:2',
'7:4',
'8:0',
'9:8',
'10:12',
'11:23',
'12:4',
'13:0']
您还可以使用功能方法:
map(lambda (i,v): v if i == 0 else str(i)+":"+v, enumerate(src))
我更喜欢功能性的方式,但据我所知,列表补偿似乎更“pythonic”。
答案 1 :(得分:1)
>>> a = ['-1', '3', '4', '5', '3', '7', '2', '4', '0', '8', '12', '23', '4', '0']
>>> a[:1] + ["{}:{}".format(x,y) for x,y in enumerate(a[1:], start=1)]
['-1', '1:3', '2:4', '3:5', '4:3', '5:7', '6:2', '7:4', '8:0', '9:8', '10:12', '11:23', '12:4', '13:0']
Enumerate允许您访问索引和元素作为元组
使用itertools.starmap
>>> import itertools
>>> a[:1] + list(itertools.starmap("{}:{}".format, enumerate(a[1:], start=1)))
['-1', '1:3', '2:4', '3:5', '4:3', '5:7', '6:2', '7:4', '8:0', '9:8', '10:12', '11:23', '12:4', '13:0']
使用map
和lambda
:
>>> a[:1] + map(lambda x:"{}:{}".format(x[0],x[1]), enumerate(a[1:], start=1))
['-1', '1:3', '2:4', '3:5', '4:3', '5:7', '6:2', '7:4', '8:0', '9:8', '10:12', '11:23', '12:4', '13:0']
如果你想存储它:
>>> a = a[:1] + ["{}:{}".format(x,y) for x,y in enumerate(a[1:], start=1)]
>>> print(a)
['-1', '1:3', '2:4', '3:5', '4:3', '5:7', '6:2', '7:4', '8:0', '9:8', '10:12', '11:23', '12:4', '13:0']
答案 2 :(得分:0)
from_list = ['-1', '3', '4', '5', '3', '7', '2', '4', '0', '8', '12', '23', '4', '0']
for i in range(1, len(from_list)):
new_ele = str(i)+':'+from_list[i]
from_list[i] = new_ele
print from_list
输出将是:
['-1', '1:3', '2:4', '3:5', '4:3', '5:7', '6:2', '7:4', '8:0', '9:8', '10:12', '11:23', '12:4', '13:0']