2016-06-07 47 views
0

我對Python很新穎,而且我剛開始學習列表解析。但是,我不能用它們重寫下面的代碼。任何幫助,將不勝感激。如何使用列表推導重新創建以下內容?

for i in range(len(table)): 
    table[i*2] += " |" 
    table.insert(2*i + 1, "-"*(len(table[0]))) 

這是一個功能,通過增加其漂亮的打印表格的一部分「|」到每一行,然後在下面一行插入一整行「 - 」。

+0

是'table'本身可迭代的嗎? – castis

+0

要澄清你想要的東西,請在你的問題中添加一個例子。你沒有包含破折號的換行符,所以我不完全確定你想要什麼。 – Prune

+0

另請輸入樣本輸入 – rrauenza

回答

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])) 

即使它不使用列表理解,它可能是更直接的理解。

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) 
相關問題