亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

遍歷字典并獲取 TypeError: 'in <string>' requires string

遍歷字典并獲取 TypeError: 'in <string>' requires string

一只甜甜圈 2022-12-27 15:47:59
我正在嘗試遍歷字符串列表,并根據單詞字典匹配/打印出這些字符串中的任何一個。我似乎收到以下錯誤,但不太確定原因。錯誤:TypeError:'in' 需要字符串作為左操作數,而不是列表這是我正在使用的當前代碼:data = ["Great price on the dewalt saw", "cool deal, love it", "nice find", "definitely going to buy"]words = {'price': ['price', 'compare', '$', 'percent', 'money']}for d in data:    for word in words.values():        if word in d:            print('Results:')            print(d)理想情況下,我想打印出包含任何價格鍵值的所有字符串。
查看完整描述

3 回答

?
桃花長相依

TA貢獻1860條經驗 獲得超8個贊

word 正在返回 a list。您需要循環/迭代該列表(單詞)。您可以通過以下方式完成它 -


data = ["Great price on the dewalt saw", "cool deal, love it", "nice find", "definitely going to buy"]

words = {'price': ['price', 'compare', '$', 'percent', 'money']}


for d in data:

    for word in words.values():

        for s in word :

            if s in d:

                print('Results:')

                print(d)

words.values()上面的代碼將查找字典單詞中的值數組(即 - 中的任何列表)中的任何字符串是否是任何字符串的一部分data。


希望能幫助到你 !


查看完整回答
反對 回復 2022-12-27
?
不負相思意

TA貢獻1777條經驗 獲得超10個贊

您在這里遇到的問題是您有一個列表作為值,因此您的調用words.values()返回一個列表,該列表在內部包含另一個列表。您可以將其更改為for word in words['price']if you will only have a price key,或者您可以這樣更改它:


>>> words = {'price': ['price', 'compare', '$', 'percent', 'money']}

>>> [word for wordlist in words.values() for word in wordlist]

['price', 'compare', '$', 'percent', 'money']


查看完整回答
反對 回復 2022-12-27
?
慕田峪9158850

TA貢獻1794條經驗 獲得超7個贊

可能是提高接受答案效率的好主意。


下面是一個提高時間復雜度的偽代碼(基于輸入)。


visited_dict = {}

results = {}

for d in data:

    for k, word in words.items():

        can_stop = False

        res_val = []

        for s in word:

            # if same words from another key is searched

            # Ex: words = {'price': ['price', 'compare', '$', 'percent', 'money'],

            #               'price2':[ 'price', 'something', 'somethingelse']}

            # In this case - get the result from visited dictionary to avoid 

            if s in visited_dict and s not in visited_dict[s]:

                # save it to results 

                # skip further steps

                continue


            if s in d and s not in res_val:

                # store it results

                res_val.append(d)

                # update visited dict

                visited_dict[s] = d

            # Save the result to final key to result map

            results[k] = res_val  # {'price': 'Great price on the dewalt saw'}


            # To avoid duplicate

            if res_val:

                break

注意:它沒有經過測試或完全實現的代碼。是的,一旦正確實施,它可能會增加空間復雜性。


查看完整回答
反對 回復 2022-12-27
  • 3 回答
  • 0 關注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號