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

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

修改代碼以處理一長串字符串

修改代碼以處理一長串字符串

開滿天機 2022-10-11 21:19:02
我想為一項任務準備一長串數據。我已經能夠將在單個實例上完成任務的代碼放在一起,但現在我想讓它通過一個列表運行。以下是我嘗試過的。用于測試的單個實例......sentences = ['if the stimulus bill had become hamstrung by a filibuster threat or recalcitrant conservadems']antecedents = ['bill had become hamstrung by']實際用例是 pandas 數據框中的兩列,我已將其轉換為列表f = tra_df['sentence'].tolist()b = tra_df['antecedent'].tolist()單個用例的代碼....results =[]ous = 1ayx = ' '.join([str(elem) for elem in antecedents])ayxx = ayx.split(" ")antlabels = []    for i in range(len(ayxx)):    antlabels.append(ous)    lab = ' '.join([str(elem) for elem in antlabels])     # Build the regex string requiredrx = '({})'.format('|'.join(re.escape(el) for el in antecedents))     # Generator to yield replaced sentencesit = (re.sub(rx, lab, sentence) for sentence in sentences)     # Build list of paired new sentences and old to filter out where not the sameresults = ([new_sentence for old_sentence, new_sentence in zip(sentences, it) if old_sentence != new_sentence])# replace other non 1 values with 0nw_results = ' '.join([str(elem) for elem in results])ew_results= nw_results.split(" ")new_results = ['0' if i is not '1' else i for i in ew_results]labels =([int(e) for e in new_results]) labels這就是我得到的結果[0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]大列表的稍微修改的代碼for sentences, antecedents in zip(f, b):    gobels = []    #def format_labels(antecedents,sentences):    results =[]    #lab =[]    ous = 1    ayx = ' '.join([str(elem) for elem in antecedents])    ayxx = ayx.split(" ")    antlabels = []        for i in range(len(ayxx)):        antlabels.append(ous)        lab = ' '.join([str(elem) for elem in antlabels])現在,我得到一個只有 1 的長列表,而不是包含 0 和 1 的字符串列表......有什么問題?
查看完整描述

1 回答

?
牧羊人nacy

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

像這樣的東西可能會更好地擴展??赡苓€有一種更 Pythonic 的方式來執行此操作。


a = '1 2 3 4 5'

b = '3 4 6'


a = a.split()

b = b.split()


for idx, val in enumerate(b):

    try:

        a[a.index(val)] = True

    except ValueError:

        pass


for idx, val in enumerate(a):

    if val is not True:

        a[idx] = False


print([1.0 if i else 0.0 for i in a])

# [0.0, 0.0, 1.0, 1.0, 0.0]


查看完整回答
反對 回復 2022-10-11
  • 1 回答
  • 0 關注
  • 111 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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