我有这段代码可以工作,但我想使用ScoreList1
作为嵌套列表的一部分,但要求的是字符串而不是列表。你知道吗
我需要它来处理列表,因为我有一个附加到列表的输入。你知道吗
ScoreList1= ['04', '05', '01', '07', '08']
nestedList = [["Judge","01","02","03","04","05"],
["Couple A","10","06","03","04","05"],
["Couple B","01","02","03","04","05"],
["Couple C","07","10","03","04","05"],
["Couple D","01","02","10","04","05"],]
for item in nestedList:
print(
": "+item[0] + " "*(9-len(item[0]))+": "+
item[1] + " "*(3-len(item[1]))+": "+
item[4] + " "*(3-len(item[4]))+": "+
item[2] + " "*(3-len(item[2]))+": "+
item[3] + " "*(3-len(item[3]))+": "+
item[5] + " "*(3-len(item[5]))+": ")
这是我的预期输出:
: Judge : 01 : 04 : 02 : 03 : 05 :
: Couple A : 10 : 04 : 06 : 03 : 05 :
: Couple B : 01 : 04 : 02 : 03 : 05 :
: Couple C : 07 : 04 : 10 : 03 : 05 :
: Couple D : 01 : 04 : 02 : 10 : 05 :
但a线在哪,我要记分表1中的数字
编辑时间:
ScoreList1= ['04', '05', '01', '07', '08']
ScoreList2= ['07', '02', '01', '02', '08']
nestedList = [["Judge","01","02","03","04","05"],
["Couple A","10","06","03","04","05"],
["Couple B","01","02","03","04","05"],
["Couple C","07","10","03","04","05"],
["Couple D","01","02","10","04","05"],]
for item in nestedList:
row = item[:1] + ScoreList1 if item[0] == "Couple A" else item
print(": {:<8} ".format(row[0])
+ "".join(": {:<2} ".format(field) for field in row[1:]))
在B组旁边需要记分表2
编辑2:
ScoreList1= ['04', '05', '01', '07', '08']
ScoreList2= ['07', '02', '01', '02', '08']
ScoreList3= ['02', '01', '01', '10', '08']
ScoreList4= ['01', '10', '02', '10', '09']
ScoreList5= ['02', '08', '01', '10', '01']
ScoreList6= ['01', '07', '01', '01', '01']
nestedListOfNames = [["Couple A"],
["Couple B"],
["Couple C"],
["Couple D"],
["Couple E"],
["Couple F"]]
print(": Judge : 01 : 02 : 03 : 04 : 05")
print("")
substitutions = {"Couple A": ScoreList1, "Couple B": ScoreList2, "Couple C": ScoreList3, "Couple D": ScoreList4, "Couple E" : ScoreList5, "Couple F" : ScoreList6}
with open("myfile.txt",'w') as outfile:
for item in nestedListOfNames:
row = item[:1] + substitutions.get(item[0], item[1:],)
outfile.write(": {:<8} ".format(row[0])
+ "".join(": {:<2} ".format(field) for field in row[1:]))
outfile.close()
如何使用\n将文本文件的行分隔开?你知道吗
最简单的方法就是检查
"Couple A"
行,并在适当的时候使用ScoreList1
代替它的值:由于您指出现在希望按顺序打印每个子列表的元素,
print()
参数的构造可以简化:要扩展它来处理两个或多个替换,而您可以这样做:
然而,这种方法很容易变得笨拙,而且如果要处理的问题多于几个,那么它也会变得相对缓慢,因此让流程“表驱动”(使用所谓的Control Table)并编写一次处理所有案例的代码(而不是为每个案例编写小片段)会更好更快:
尝试使用内置的^{} 函数
相关问题 更多 >
编程相关推荐