2012-07-14 46 views
1

的名單說:蟒蛇搜索我只想問你如何搜索在Python元組的列表,元組

[("A","B",3),("C","D",4),("E","F",5)] 

假設爲"A", "B"用戶搜索:因爲"A", "B"是在列表中,它會增加3.和將輸出列表中再次

[("A","B",4),("C","D",4),("E","F",5)] 

如果"A", "S"用戶搜索時,程序會創建一個新的記錄,並保存在數據庫中

如果使用 collections.Counter

首先,你需要通過序列迭代並利用前兩個項目例如一個元組創建一個

[("A","S",1),("A","B",3),("C","D",4),("E","F",5)] 
+6

聽起來你應該使用字典,'collections'有'defaultdict'和'Counter'可能是有用的。 @ M.Gibson是否允許使用任何庫,比如'collections'? – jamylak 2012-07-14 11:43:03

+2

你會搜索元組中的第二個元素嗎? – Levon 2012-07-14 11:44:44

回答

6

這項任務將變得簡單。 ("A", "B")作爲關鍵和數字eg。作爲值爲3

然後你可以簡單地做c[("A", "B")] += 1例如。如果鑰匙還沒有在櫃檯上,它也會起作用。 c[("A", "S")] += 1

你可以創建一個列表,使用列表理解輸出它,但我會把它留給你,因爲這是作業。

0
lis=[["A","B",3],["C","D",4],["E","F",5]] 

def search_and_increment(local_list,search): 
    for x in local_list: 
     if search in ",".join(x[:-1]): 
      x[-1]+=1 
      return 
    else: 
     local_list.append(search.split(",")+[1]) 
     return 

輸出:

>>> search_and_increment(lis,"A,B") 
>>> lis 
[['A', 'B', 4], ['C', 'D', 4], ['E', 'F', 5]] 
>>> search_and_increment(lis,"A,S") 
>>> lis 
[['A', 'B', 4], ['C', 'D', 4], ['E', 'F', 5], ['A', 'S', 1]] 
>>> search_and_increment(lis,"A,S") 
>>> lis 
[['A', 'B', 4], ['C', 'D', 4], ['E', 'F', 5], ['A', 'S', 2]] 
>>> search_and_increment(lis,"E,F") 
>>> lis 
[['A', 'B', 4], ['C', 'D', 4], ['E', 'F', 6], ['A', 'S', 2]] 
+3

鑑於OP是一名學生,最好在答案中提出一些好的做法。 (比如不使用全局變量,或給'func'一個描述性的名字。) – millimoose 2012-07-14 11:54:15

+1

列表的* elements *是* tuples *,你的代碼和解決方案使用* lists *這當然使得這更容易,因爲list是可變的不像元組。 OP在他的問題中指定了元組。 – Levon 2012-07-14 12:14:31

0

整個事情是有點棘手,因爲元組是不可變的,這意味着它們不能被改變。相反,你必須複製並讀取它們。

如果你真的需要使用元組,這段代碼應該可以工作(儘管它可能完全不是最好的解決方案)。但是,此解決方案不會保持列表元素的順序。

否則,jamylak的解決方案看起來會更好。

def search_and_inc_list(tuple_list, search_tuple): 
    found = False 

    for index, element in enumerate(tuple_list): 
     last_index = len(search_tuple) 
     if element[0:last_index] == search_tuple: 
      new_element = element[0:last_index] + (element[last_index]+1,) 
      found = True 

      tuple_list[index] = new_element 

      # You may add break here if elements are unique 

    if found == False: 
     new_tuple = search_tuple + (1,) 
     tuple_list.append(new_tuple) 


mylist = [("A","B",3),("C","D",4),("E","F",5)] 
print(mylist) 
search_and_inc_list(mylist, ("A", "B")) 
print(mylist) 
search_and_inc_list(mylist, ("A", "C")) 

# [('A', 'B', 3), ('C', 'D', 4), ('E', 'F', 5)] 
# [('A', 'B', 4), ('C', 'D', 4), ('E', 'F', 5)] 
# [('A', 'B', 4), ('C', 'D', 4), ('E', 'F', 5), ('A', 'C', 1)]