Python 根据索引重新调整列表中元素的大小

Python 根据索引重新调整列表中元素的大小,python,Python,我在python中有一个列表,用于将数据写入命令行可执行文件的输入文件。可执行文件对某些输入字符串的长度有限制,但不是全部。是否有办法在我的“数组”中的某个位置重新调整所有元素的大小,以便: 1, test, 12, toronto 2, test, 145, montreal 3, test, 178, north bay 将成为: 1, test, 12, to 2, test, 145, mo 3, test, 178, no 就编码而言,我认为这样的东西可以迭代工作,

我在python中有一个列表,用于将数据写入命令行可执行文件的输入文件。可执行文件对某些输入字符串的长度有限制,但不是全部。是否有办法在我的“数组”中的某个位置重新调整所有元素的大小,以便:

1, test, 12, toronto  
2, test, 145, montreal  
3, test, 178, north bay
将成为:

1, test, 12, to  
2, test, 145, mo  
3, test, 178, no
就编码而言,我认为这样的东西可以迭代工作,但我更喜欢一次处理整个数组的方法

for x in list:
    x[3] = x[3][:5] #where 5 is the length
作为
i
要缩短的位置,如果它是不同的列,请在(3,5)中使用类似
i的内容

或者,如果不同的列具有不同的长度,则可以使用如下内容:

a = [[1, 'test', 12, 'toronto'], [2, 'test', 145, 'montreal']]
shorten = {1: 2, 3: 4} #shorten column 1 to length 2, and col 3 to len 4
a = [[e[:shorten[i]] if i in shorten else e for i, e in enumerate(line)] for line in a]
print (a)
输出

 [[1, 'test', 12, 'to'], [2, 'test', 145, 'mo'], [3, 'test', 178, 'no']]

首先,这里晚安。:)第二,你到底有什么问题?你所说的“一次性处理一个while数组”是什么意思?实际上是“下午好”:)这太完美了。添加的执行“i=(0或2或10)”的功能特别有用。
i=(0或2或10)
i=2
相同,不会按预期工作。您正在(0,2,10)
中查找
i。
my_list = [[1, 'test', 12, 'toronto'],
          [2, 'test', 145, 'montreal'],
          [3, 'test', 178, 'north bay']]

print map(lambda x: x[:2] + [x[3][:2]],[x for x in my_list])
 [[1, 'test', 12, 'to'], [2, 'test', 145, 'mo'], [3, 'test', 178, 'no']]