簡體   English   中英

python中的字符串操作,不同長度

[英]String Manipulation in python, different length

我有一個類似下面的字符串:

string A:     animals_goat=1; country=3 4 5; Foo=1 2 3;
string 1:     country=0 1 2; Foo=0 0 0;
string 2:     country=0 0 0; Foo=1 1 1;

我想比較不同長度的字符串,需要輸出如下所示:

animals_goat=1; country=0 1 2; Foo=0 0 0; 
animals_goat=1; country=0 0 0; Foo=1 1 1;

注意:

  1. 我正在讀取字符串1和字符串2,並將其與字符串A進行比較,然后像我一樣打印出字符串。 字符串A就像具有所有值的主字符串一樣。 目前,我在變量中有字符串A,在另一個變量中有string1和string 2。

  2. 當經過最長的字符串時,將其與元素匹配時的最短字符串進行比較,在這種情況下,我希望將最長字符串中的匹配元素替換為最短字符串中的相同元素,country = 0 1 2,其中country兩個字符串都匹配,並顯示第二個字符串值

  3. 然后,由於沒有匹配項,它將打印最長字符串中的下一個元素

  4. 短字符串中的所有元素也始終存在於長字符串中。

我試圖將變量和值放入兩個字符串的兩個單獨的列表中,但無法同時遍歷所有4個列表。 有沒有辦法做到這一點??

提供的答案有效,除了我的字符串1和字符串2作為多行字符串包含在信號變量中。

string= animals_goat=1; country=0 1 2; Foo=0 0 0;
        animals_goat=1; country=0 0 0; Foo=1 1 1;

因此,當我執行“ for string in string:”時,它給了我一個錯誤。 我現在正嘗試將其轉換為:

['animals_goat=1; country=0 1 2; Foo=0 0 0;','animals_goat=1; country=0 0 0; Foo=1 1 1;']

但是當我這樣做

string_list = [y for y in (x.strip() for x in string.splitlines()) if y]  

I end up with below: 

['animals_goat=1;'' country=0 1 2;''Foo=0 0 0;']
['animals_goat=1;'' country=0 0 0;''Foo=0 0 0;'] 

總而言之,我們需要處理的每一行都需要更新主數據。 這里的方法是將主數據解析為可以輕松轉換為字典的項目列表。 然后,一次只占用一行,我們創建該字典並使用該行中解析的值對其進行更新。 然后打印結果。

根據更新的問題,我現在有lines變量由幾個換行符分隔的行的單個字符串組成:

# Input data
master = 'animals_goat=1; country=3 4 5; Foo=1 2 3;'
lines = """country=0 1 2; Foo=0 0 0;
country=0 0 0; Foo=1 1 1;"""

# Extract info from master string
items = [s.strip().split('=') for s in master.split(';') if s]
keys = [item[0] for item in items]

# Process input lines, one at a time
for line in lines.splitlines():
    d = dict(items)
    new = dict(s.strip().split('=') for s in line.split(';') if s)
    d.update(new)
    for k in keys:
        print '%s=%s;' % (k, d[k]),
    print ""

產生輸出:

animals_goat=1; country=0 1 2; Foo=0 0 0; 
animals_goat=1; country=0 0 0; Foo=1 1 1; 

暫無
暫無

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

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