Взятие наименьшего предмета (строки) из списка - PullRequest
0 голосов
/ 14 декабря 2018
mylist = ['breast:entire breast quadrant ', 'breast:entire breast ', 'breast:entire breast and endocrine system ', 'breast:entire breast quadrant ', 'breast:entire breast ', 'breast:entire breast and endocrine system ', 'chest:entire chest wall ', 'chest:entire chest wall artery ', 'chest:entire chest and abdomen and pelvis ', 'chest:entire chest wall ', 'chest:entire chest wall artery ', 'chest:entire chest and abdomen ', 'chest:entire chest and abdomen and pelvis ', 'chest:entire chest wall ', 'chest:entire chest wall artery ', 'chest:entire chest and abdomen ', 'chest:entire chest wall ', 'chest:entire chest wall artery ']

В приведенном выше списке у меня есть два ключевых слова (грудь и грудь) и соответствующие значения.Мне нужно выбрать наименьшее значение ( по количеству слов ) для каждого ключевого слова .

Я бы предпочел подобрать 1) 'breast:entire breast ' 2) 'chest:entire chest wall '

Не могли бы вы помочь?Быть выполненным в Python.

Ответы [ 3 ]

0 голосов
/ 14 декабря 2018
mylist = ['breast:entire breast quadrant ', 'breast:entire breast ', 'breast:entire breast and endocrine system ', 'breast:entire breast quadrant ', 'breast:entire breast ', 'breast:entire breast and endocrine system ', 'chest:entire chest wall ', 'chest:entire chest wall artery ', 'chest:entire chest and abdomen and pelvis ', 'chest:entire chest wall ', 'chest:entire chest wall artery ', 'chest:entire chest and abdomen ', 'chest:entire chest and abdomen and pelvis ', 'chest:entire chest wall ', 'chest:entire chest wall artery ', 'chest:entire chest and abdomen ', 'chest:entire chest wall ', 'chest:entire chest wall artery ']

string1 = 'breast:'
string2 = 'chest:'
c1 = float("inf")
c2 = float("inf")
for x in mylist:
    if 'breast' in x :
        c_idx = x.index(':')
        x = x [ c_idx+1 : ]
        cnt = x.count(" ")
        if cnt < c1 :
            string_b = x
            c1 = cnt
        else :
            continue
    elif 'chest' in x :
        c_idx = x.index(':')
        x = x [ c_idx+1 : ]
        cnt = x.count(" ")
        if cnt < c2 :
            string_c = x
            c2 = cnt
        else :
            continue
print(string1+string_b)
print(string2+string_c)

Надеюсь, это поможет.

0 голосов
/ 14 декабря 2018

Другая опция

sublisted = [ x.split(":") for x in set(mylist)]

breast = min([ item[1] for item in sublisted if item[0] == "breast" ], key=len)
chest = min([ item[1] for item in sublisted if item[0] == "chest" ], key=len)

print(breast) #=> entire breast 
print(chest) #=> entire chest wall  


Вы можете настроить или построить метод для получения желаемого формата строки, например:
sublisted = [ x.split(":") for x in set(mylist) ]

def find_min(lst, str):
  found = min([ item[1] for item in sublisted if item[0] == str ], key=len)
  return str + ': ' + found

keys = { x[0] for x in sublisted }
for k in keys:
  print(find_min(sublisted, k))
# chest: entire chest wall 
# breast: entire breast 
0 голосов
/ 14 декабря 2018

вы можете сделать это, используя отсортированный список и дикт.сначала вы можете создать список списков:

[x.split(':') for x in mylist]

результат:

[['breast', 'entire breast quadrant '],
 ['breast', 'entire breast '],
 ['breast', 'entire breast and endocrine system '],
 ['breast', 'entire breast quadrant '],
 ['breast', 'entire breast '],
 ['breast', 'entire breast and endocrine system '],
 ['chest', 'entire chest wall '],
 ['chest', 'entire chest wall artery '],
 ['chest', 'entire chest and abdomen and pelvis '],
 ['chest', 'entire chest wall '],
 ['chest', 'entire chest wall artery '],
 ['chest', 'entire chest and abdomen '],
 ['chest', 'entire chest and abdomen and pelvis '],
 ['chest', 'entire chest wall '],
 ['chest', 'entire chest wall artery '],
 ['chest', 'entire chest and abdomen '],
 ['chest', 'entire chest wall '],
 ['chest', 'entire chest wall artery ']

теперь мы можем упорядочить его по первому значению и длине слов во втором значении

sorted(
     [x.split(':') for x in mylist],
     key=lambda x: (x[0],len(x[1].split())),
     reverse=True
)

мы используем обратное, чтобы положить минимальное значение в конец отсортированного списка, и в результате получим:

[['chest', 'entire chest and abdomen and pelvis '],
 ['chest', 'entire chest and abdomen and pelvis '],
 ['chest', 'entire chest wall artery '],
 ['chest', 'entire chest wall artery '],
 ['chest', 'entire chest and abdomen '],
 ['chest', 'entire chest wall artery '],
 ['chest', 'entire chest and abdomen '],
 ['chest', 'entire chest wall artery '],
 ['chest', 'entire chest wall '],
 ['chest', 'entire chest wall '],
 ['chest', 'entire chest wall '],
 ['chest', 'entire chest wall '],
 ['breast', 'entire breast and endocrine system '],
 ['breast', 'entire breast and endocrine system '],
 ['breast', 'entire breast quadrant '],
 ['breast', 'entire breast quadrant '],
 ['breast', 'entire breast '],
 ['breast', 'entire breast ']]

и теперь сделаем дикт из отсортированного списка, диктат имеетуникальные ключи, поэтому при обработке результата будут приниматься последние значения для каждого первого значения:

dict(sorted( 
    [x.split(':') for x in mylist], 
    key=lambda x: (x[0],len(x[1])), 
    reverse=True 
    )) 

результат равен

{'chest': 'entire chest wall ', 'breast': 'entire breast '}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...