如何简化变量的使用?

时间:2018-11-02 05:59:09

标签: python python-3.x

python的新手。如何使用变量将其简化为一行?

print (my_list [0] + " " + my_list [1] + " - " + my_list [2] + " - " + my_list [3] + " , " + my_list [4] + " , " + my_list [5])
print (my_list [6] + " " + my_list [7] + " - " + my_list [8] + " - " + my_list [9] + " , " + my_list [10] + " , " + my_list [11])
print (my_list [12] + " " + my_list [13] + " - " + my_list [14] + " - " + my_list [15] + " , " + my_list [16] + " , " + my_list [17])
print (my_list [18] + " " + my_list [19] + " - " + my_list [20] + " - " + my_list [21] + " , " + my_list [22] + " , " + my_list [23])
print (my_list [24] + " " + my_list [25] + " - " + my_list [26] + " - " + my_list [27] + " , " + my_list [28] + " , " + my_list [29])
print (my_list [30] + " " + my_list [31] + " - " + my_list [32] + " - " + my_list [33] + " , " + my_list [34] + " , " + my_list [35])
print (my_list [36] + " " + my_list [37] + " - " + my_list [38] + " - " + my_list [39] + " , " + my_list [40] + " , " + my_list [41])
print (my_list [42] + " " + my_list [43] + " - " + my_list [44] + " - " + my_list [45] + " , " + my_list [46] + " , " + my_list [47])
print (my_list [48] + " " + my_list [49] + " - " + my_list [50] + " - " + my_list [51] + " , " + my_list [52] + " , " + my_list [53])
print (my_list [54] + " " + my_list [55] + " - " + my_list [56] + " - " + my_list [57] + " , " + my_list [58] + " , " + my_list [59])

4 个答案:

答案 0 :(得分:3)

如果您使用python3.6, 您可以使用fstring,它也可以帮助您格式化字符串

my_list=[i for i in range(60)]
def printarray(listarray):
        print(f"{listarray[0]} {listarray[1]} - {listarray[2]} - {listarray[3]} , {listarray[4]} , {listarray[5]}")
for i in range(0,60,6):
        printarray(my_list[i:i+6])

输出

0 1 - 2 - 3 , 4 , 5
6 7 - 8 - 9 , 10 , 11
.....
48 49 - 50 - 51 , 52 , 53
54 55 - 56 - 57 , 58 , 59

答案 1 :(得分:0)

您可以使用for循环将其简化为一行:

for i in range(0, 60, 6):  print(my_list [i] + " " + my_list [i+1] + " - " + my_list [i+2] + " - " + my_list [i+3] + " , " + my_list [i+4] + " , " + my_list [i+5])

答案 2 :(得分:0)

total_elements = 60
elements_in_one_line = 6
for i in range(total_elements ):
    if i%elements_in_one_line  == 0:
        print()
    print(my_list[i],end=' ')

答案 3 :(得分:0)

分为6个元素的子数组,并将每个元素附加到子数组中。

一行代码是

composite_list = [ my_list[x] + " " + my_list[x+1] + " - " + my_list[x+2] + " - " + my_list[x+3] + " , " + my_list[x+4] + " , " + my_list[x+5]  for x in range(0, len(my_list),6)]

请尝试以下示例代码。

import random

my_list = map(str, random.sample(xrange(100), 60))
print(my_list)
composite_list = [ my_list[x] + " " + my_list[x+1] + " - " + my_list[x+2] + " - " + my_list[x+3] + " , " + my_list[x+4] + " , " + my_list[x+5]  for x in range(0, len(my_list),6)]
print(composite_list)