2016-10-05 80 views
1

我有一個字符串列表的列表:加法計數器/索引列表的列表在Python

listBefore = [['4', '5', '1', '1'], 
       ['4', '6', '1', '1'], 
       ['4', '7', '8', '1'], 
       ['1', '2', '1', '1'], 
       ['2', '3', '1', '1'], 
       ['7', '8', '1', '1'], 
       ['7', '9', '1', '1'], 
       ['2', '4', '3', '1']] 

,我想每個列表的中間添加一個計數器/索引,使列表看起來像:

listAfter = [['4', '5', '1', '1', '1'], 
      ['4', '6', '2', '1', '1'], 
      ['4', '7', '3', '8', '1'], 
      ['1', '2', '4', '1', '1'], 
      ['2', '3', '5', '1', '1'], 
      ['7', '8', '6', '1', '1'], 
      ['7', '9', '7', '1', '1'], 
      ['2', '4', '8', '3', '1']] 

這樣做最簡單的方法是什麼?我大概可以遍歷列表並添加索引,但是有更清晰的方法嗎?

乾杯, 凱特

編輯: 我寫的作品對我來說,代碼:

item = 1 
for list in listBefore: 
    list.insert(2,str(item)) 
    item = item + 1 
print listBefore 

我想知道是否有另一種方式來讓更多的有效或一步完成。

+1

看起來你要我們寫一些代碼給你。儘管許多用戶願意爲遇險的編碼人員編寫代碼,但他們通常只在海報已嘗試自行解決問題時才提供幫助。展示這一努力的一個好方法是包含迄今爲止編寫的代碼,示例輸入(如果有的話),期望的輸出以及實際獲得的輸出(輸出,回溯等)。您提供的細節越多,您可能會收到的答案就越多。檢查[FAQ](http://stackoverflow.com/tour)和[如何提問](http://stackoverflow.com/questions/how-to-ask)。 – TigerhawkT3

+0

我同意你應該嘗試寫一些自己,看看有什麼作用。對於一些幫助,請查看'enumerate'。 – CasualDemon

回答

1

你可以用一個列表理解在父列表與enumerate()執行此

listAfter = [listBefore[i][:len(listBefore[i])/2] + [str(i+1)] + listBefore[i][len(listBefore[i])/2:] for i in range(len(listBefore))] 
2

迭代與列表元素相處計數器(在下面的例子作爲i)。在子列表中,使用list.insert(index, value)方法在子列表的中間插入i注意:計數器的值即i將爲int類型,因此您必須在插入前將其明確地鍵入爲str作爲str(i)。下面是示例代碼:

for i, sub_list in enumerate(my_list, 1): # Here my_list is the list mentioned in question as 'listBefore' 
    sub_list.insert(len(sub_list)/2, str(i)) 

# Value of 'my_list' 
# [['4', '5', '1', '1', '1'], 
# ['4', '6', '2', '1', '1'], 
# ['4', '7', '3', '8', '1'], 
# ['1', '2', '4', '1', '1'], 
# ['2', '3', '5', '1', '1'], 
# ['7', '8', '6', '1', '1'], 
# ['7', '9', '7', '1', '1'], 
# ['2', '4', '8', '3', '1']] 
0

你應該瞭解enumerate,它可以讓你遍歷兩個迭代器列表 - 一個(str_list在這種情況下) holds the current item in the list, and the other ( i`)持有它的指數在列表中。

for i,str_list in enumerate(listBefore): 
    listBefore[i] = str_list[:len(str_list)//2] + [str(i+1)] + str_list[len(str_list)//2:] 
0
>>> data = [['4', '5', '1', '1'], 
      ['4', '6', '1', '1'], 
      ['4', '7', '8', '1'], 
      ['1', '2', '1', '1'], 
      ['2', '3', '1', '1'], 
      ['7', '8', '1', '1'], 
      ['7', '9', '1', '1'], 
      ['2', '4', '3', '1']] 
>>> print [row[:len(row)//2] + [str(i)] + row[len(row)//2:] 
      for i, row in enumerate(data, start=1)] 
[['4', '5', '1', '1', '1'], 
['4', '6', '2', '1', '1'], 
['4', '7', '3', '8', '1'], 
['1', '2', '4', '1', '1'], 
['2', '3', '5', '1', '1'], 
['7', '8', '6', '1', '1'], 
['7', '9', '7', '1', '1'], 
['2', '4', '8', '3', '1']]