簡體   English   中英

給定字符串中的一組字母如何在python中獲取字符串中的剩余字母

[英]Given a set of letters in a string how to get remaining letters in the string in python

我有一個像'LETTER'的字符串,當我用前一個字符串檢查該字符串時,我還有另一個字符串“ LTR”,其余字母為“ ETE”我怎么能從python的主字符串中提取這個字符串。 字母的順序無關緊要,我們應該獲取剩余的字母

使用difflib庫中的ndiff()

>>> from difflib import *
>>> list(ndiff("LETTER","LTR"))
['  L', '- E', '  T', '- T', '- E', '  R']

#so filter out letters which doesn't have '-'

>>> ''.join(x.strip('-').strip() for x in filter(lambda x:'-' in x,ndiff("LETTER","LTR")))
'ETE'

>>> ''.join(x.strip('-').strip() for x in filter(lambda x:'-' in x,ndiff("stack","tc")))
'sak'

您可以使用Counter() ,以防字母順序無關緊要:

>>> from collections import Counter
>>> str1="LETTER"
>>> str2="LTR"
>>> c=Counter(str1)-Counter(str2)
>>> c
Counter({'E': 2, 'T': 1})
>>> ''.join(x*c[x] for x in c)
'EET

流行的問題:-)我認為這是一個很容易理解的問題:

s=list("LETTER")                                  
p=list("LTR")                                         
while p: s.remove(p.pop())                            

現在

print("".join(s))

打印“ ETE”

>>> x = "LETTER"
>>> for c in "LTR":
...     if c in x:
...        p = x.find(c)
...        if p < len(x)-1:
...           x = x[:p]+x[p+1:]
...        else:
...           x = x[:p]
...
>>> x
'ETE'

這是一個相當簡單易讀的解決方案,可以正確保留輸入字符串的順序和重復項:

def omit(s, discard):
    discard = list(discard)
    for c in s:
        if c not in discard:
            yield c
        else:
            discard.remove(c)

>>> ''.join(omit('LETTER', 'LTR'))
'ETE'
#!/bin/env python

def str_diff(s, rem):
    for x in rem:
        pos = s.find(x)
        if pos >= 0: s = s[:pos] + s[pos+1:]

    return s

print str_diff("LETTER", "LTR")    # ETE
print str_diff("LETTER", "LTTR")   # EE
print str_diff("LETTER", "LTRxyz") # ETE

這似乎可以完成您想做的事情。 它保留原始順序,適用於“刪除集”中同一字母的倍數,並且如果“刪除集”中包含原始字符串中未包含的字符,則不會拒絕。

>>> x = "LETTER"
>>> r = "LTR"
>>> y = x
>>> for c in r:
...     y = y.replace(c, '', 1)
... 
>>> y
'ETE'
def remaining(my_string, my_string_2):
    output = ""

    i = 0
    j = 0
    while i < len(my_string) and j < len(my_string_2):
        if my_string[i] != my_string_2[j]:
            output += my_string[i]
        else:    
            j += 1
        i+=1
    if i < len(my_string):
        output+=my_string[i:len(my_string)]

    return output

result = remaining("LETTER", "LTR")

print result

返回“ ETE”

l1='LETTER'
l2='LTR'
occur=[]
for i in range(0,len(l1)):
    if l1[i] in occur:
        print l1[i]

    if l1[i] in l2:
        occur.append(l1[i])
    else:
        print l1[i]

暫無
暫無

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

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