简体   繁体   中英

Get unique list of strings by string substring

I made this working code but maybe it's possible to make it shorter?

sents_str = 'dimplegalla:28082000 dimplegalla:28082000'

sents = sents_str.split(' ')
uniqueList = []
uniqueRes = []

for letter in sents:
    if letter.split(':')[1] not in uniqueList:
        uniqueList.append(letter.split(':')[1])
        uniqueRes.append(letter)
print(uniqueRes)

How about this:

In [1]: sents_str = 'dimplegalla:28082000 dimplegalla:28082000'

In [2]: list(set(sents_str.split()))
Out[2]: ['dimplegalla:28082000']

Yes:

list({sub for sub in sents_str.split()})

try this:

sents_str = 'dimplegalla:28082000 dimplegalla:28082000'
uniqueList= [l.split(':')[1] for l in list(set(sents_str.split(' ')))]
uniqueRes = list(set(sents_str.split(' ')))
print(uniqueList)
print(uniqueRes)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM