我是Python的新手,我刚刚开始掌握列表推导的问题。但是,我无法使用它们重写以下代码。任何帮助都将不胜感激。
for i in range(len(table)):
table[i*2] += " |"
table.insert(2*i + 1, "-"*(len(table[0])))
这是函数的一部分,它通过添加" |"来打印表格。每隔一行插入一行" - " s到下一行。
答案 0 :(得分:3)
table = [ "a", "b", "c", "d"]
table[:] = [x for i in table for x in [i + ' |', '-'*(2+len(table[0]))]]
print (table)
# Result:
# ['a |', '---', 'b |', '---', 'c |', '---', 'd |', '---']
作为您所写内容的可读替代方案,请尝试以下方法:
newtable = []
for i in table:
newtable.append(i + ' |')
newtable.append('-'*len(newtable[0]))
即使它没有使用列表理解,但它可能更容易理解。
答案 1 :(得分:0)
您的代码仅相当于连接:
In [1]: table = ["foo","bar", "foobar","foob","barf"]
In [2]:
In [2]: for i in range(len(table)):
...: table[i*2] += " |"
...: table.insert(2*i + 1, "-"*(len(table[0])))
...:
In [3]: print("".join(table))
foo |-----bar |-----foobar |-----foob |-----barf |-----
In [4]: table = ["foo","bar", "foobar","foob","barf"]
In [5]: print("".join([ele + " |-----" for ele in table]))
foo |-----bar |-----foobar |-----foob |-----barf |-----
显然,你会用硬编码的------
替换表格[0] + 2的长度来计算你在循环中用" |"
添加的2个额外字符:
table = ["foo", "bar", "foobar", "foob", "barf"]
form = " |" + "-" * (2 + len(table[0]))
print("".join([ele + form for ele in table]))
但是如果你想要某种格式,str.join
可能更合适:
" |{}".format("-" * (2 + len(table[0]))).join(table)