Home > Blockchain >  find a text in elements of list if exists append it to a new list
find a text in elements of list if exists append it to a new list

Time:12-30

list = ['0-0-0-0-0-4-0', '0-0-0-1-0-4-2', '0-0-3-0-0-80-0', '0-0-3-1-0-81-0', '0-0-3-0-0-82-0']

appendlist = ['0-0-3-0']

search for first 7 digit of element like that 0-0-3-0 occurance 2 times

'0-0-3-0-0-80-0', '0-0-3-0-0-82-0' then if 11th-12th digits of elements(80-82) different code will append the first 7 digit like appendlist = ['0-0-3-0']

I can't use any library import !!! only loops

info =['0-0-0-0-0-4-0', '0-0-0-1-0-4-2', '0-0-3-0-0-80-0', '0-0-3-1-0-81-0', '0-0-3-0-0-82-0']

infolist = []

for n in info
    if info.count(n[0:7]) > 1
        if n not in infolist
            infolist.append(n)
        end
    end
end

Print(infolist)

I tried this but list output is empty

I tried count method

CodePudding user response:

info.count() looks for exact matches, not substrings. You need to count the number of items that start with n[0:7]. That can be done with the sum() function.

You can prevent duplicates by making infolist a set rather than a list. If you need a list, you can turn it into a list at the end.

infolist = set()

for n in info:
    if sum(item.startswith(n[0:7]) for item in info) > 1:
        infolist.add(n)

infolist = list(infolist)
  • Related