簡體   English   中英

將字符串附加到列表

[英]Appending strings to a list

新手問題在這里。

我正在尋找各種字符串元素的每一個組合,然后想將它們放入一個列表中。

import itertools 

mydata = [ ]

main = [["car insurance", "auto insurance"], ["insurance"], ["cheap", "budget"],
      ["low cost"], ["quote", "quotes"], ["rate", "rates"], ["comparison"]]

def twofunc(one, two):
    for a, b in itertools.product(main[one], main[two]):
        print a, b

def threefunc(one, two, three):
    for a, b, c in itertools.product(main[one], main[two], main[three]):
        print a, b, c

twofunc(2, 0)  #extremely inefficient to just run these functions over and over. alternative?
twofunc(3, 0)
twofunc(0, 4)
twofunc(0, 5)
twofunc(0, 6)
threefunc(2, 0, 4)
threefunc(3, 0, 4)
threefunc(2, 0, 5)
threefunc(3, 0, 5)
threefunc(2, 0, 6)
threefunc(3, 0, 6)

上面的代碼只是打印出每個排列,但不會 append 將值添加到列表中。 我已經嘗試了 append 方法的各種變體,但仍然沒有運氣。

誰能幫我將這些值放入 mydata 列表中。 我假設每個字符串都必須是一個單獨的列表,所以它最終會成為一個列表列表。 它應該如下所示,但將來我還需要一些方法來包含“標簽”,或者只是字符串是否包含值的值。

[["cheap car insurance"],
["cheap auto insurance"],
["budget car insurance"],
["budget auto insurance"],
["low cost car insurance"],
["low cost auto insurance"],
...

所以,最終,將結束:1 表示字符串包含單詞 car/cheap,0 表示不包含。 我提到這個的原因只是為了詢問一個列表是否是這個任務的正確數據結構。

                         car        cheap 
cheap car insurance       1            1
cheap auto insurance      0            1 
budget car insurance      1            0
budget auto insurance     0            0

任何人都可以幫忙。

我已經在 R 中完成了這個任務,這很適合這個任務,只是想在 Python 中重現它。

要將 twofunc 和 threefunc 的返回值放入一個列表中,您可以更改 return 語句以便返回列表。 然后append將結果保存到 mydata。 以下是 twofunc 的示例:

def twofunc(one, two):
    for a, b in itertools.product(main[one], main[two]):
        return [a, b]

mydata.append(twofunc(2,0))

也就是說,我不熟悉 R,所以顯然不知道您可能在那里使用什么數據結構。 對於您既定的目標,將其保留在列表中可能會變得復雜。 但是,創建一個簡單的 class 來執行此操作應該不會太困難。 然后,您可以獲得一個由該 class 的實例組成的列表。

main = [["car", "auto"], ["insurance"],["cheap", "budget"]]

reduce(lambda x,y: [e+' '+f for e,f in itertools.product(x,y)],main)

或者

reduce(lambda x,y: [' '.join([e,f]) for e,f in itertools.product(x,y)],main)

后者應該更快
結果是:

['car insurance cheap', 'car insurance budget', 'auto insurance cheap', 'auto insurance budget']

首先,您不需要單獨編寫 twofunc 和 threefunc:

def nfunc(strings, indices):
    """call as nfunc(main,(2,0)) or nfunc(main, (2,0,4))"""
    selected_strings=map(lambda index:strings[index], indices)
    return itertools.product(*selected_strings)

請注意,這只是返回可迭代的 object,因此會延遲計算。

現在,我們可以將命令代碼中的索引列表拆分為列表,就像您對字符串所做的那樣,因此您無需重寫任何 function 調用來更改索引:

index_list=[(2, 0),(3, 0),...,(2, 0, 4),(3, 0, 4),...,(3, 0, 6)]

要獲取惰性結果列表,您現在可以編寫:

lazy_results=[nfunc(main, indices) for indices in index_list]
-> [itertools.product at 0xblahblah, itertools.product at 0xblahblah, ...]

強制評估結果:

eager_results=[list(lazy) for lazy in lazy_results]
-> [[("cheap","car insurance"),("budget","car insurance"), ...

將元組展平為字符串:

str_results=[[' '.join(rtuple) for rtuple in result] for result in eager_results]
-> [["cheap car insurance", "budget car insurance", ...

如果需要,您可以添加任意標簽:

tag_index_list=[(tag_1,(2,0)), ... (tag_n, (3, 0, 6))]
tag_results=[(tag, nfunc(main, indices)) for (tag, indices) in tag_index_list]

根據需要做什么,最好為您的結果集編寫一個 class ; 但是,如果您單步執行上面的代碼,您將了解使用嵌套列表和元組的外觀。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM