如何在Python2.7中格式化元组列表?

2024-04-25 20:55:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这里问了前面的一个问题,得到了一个很好的答案:如何在python2.7中为嵌套列表中的项自动分配一个变量?在输出时要执行以下操作:

上一个问题:

nList = [[0,0,0],[3,2,1]],\ [[]],\ [[100,1000,110]],\ [[0,0,0],[300,400,300],[300,400,720],[0,0,120],[100,0,1320],[30,500,1450]] 

I need to assign automatic variables to the items before each '\'. for example, distance1 = [[0,0,0],[3,2,1]], distance2=[[]], distance3= [[100,1000,110]] etc. However, this needs to be automatic for each distance'n' rather than me taking indexes from mList and assigning them to variable distance'n

现在,我需要格式化distanceN变量,以便尝试打印distance4(例如)将得到以下输出:

>>0 metres, 0 metres, 0 seconds
>>300 metres, 400 metres, 300 seconds
>>300 metres, 400 metres, 720 seconds
>>0 metres, 0 metres, 120 seconds
>>100 metres, 0 metres, 1320 seconds
>>30 metres, 500 metres, 1450 seconds

任何帮助都将不胜感激。非常感谢。你知道吗


Tags: theto答案列表foritemsvariablesneed
1条回答
网友
1楼 · 发布于 2024-04-25 20:55:23

不需要将nList转换成任何东西;不需要转换成命名变量,也不需要转换成字典。它作为一个元组工作得很好(顺便说一下,它是而不是列表-它是列表的元组)。你可以把它命名为distances。你知道吗

distances = [[0,0,0],[3,2,1]], [[]], [[100,1000,110]], [[0,0,0],[300,400,300],[300,400,720],[0,0,120],[100,0,1320],[30,500,1450]]

# "distance4" accessed by index 3 in tuple
for distance in distances[3]:
    print '{} metres, {} metres, {} seconds'.format(*distance)

输出

0 metres, 0 metres, 0 seconds
300 metres, 400 metres, 300 seconds
300 metres, 400 metres, 720 seconds
0 metres, 0 metres, 120 seconds
100 metres, 0 metres, 1320 seconds
30 metres, 500 metres, 1450 seconds

相关问题 更多 >