根据单词所属的类别集重新排列字符串中的单词

2024-06-25 06:19:48 发布

您现在位置:Python中文网/ 问答频道 /正文

如何根据字符串所属的类别重新排列它?假设我有以下几套:

dogs = {'husky', 'chihuahua', 'labrador', 'beagle'} 
flowers = {'dandelion', 'rose', 'tulip'} 
colours = {'blue', 'yellow', 'green', 'red', 'pink'}

然后,假设我想输入一个字符串,并根据它们的类别重新排列单词

'husky tulip red orange'

将成为

'red orange husky tulip'

顺序是先是颜色,然后是狗,然后是花。也许可以按顺序创建一个类别列表?不太确定我会怎么做


Tags: 字符串顺序red类别coloursorangedogshusky
3条回答

使用带有sorted的键函数:

def ref(s):
    dogs = {'husky', 'chihuahua', 'labrador', 'beagle'} 
    flowers = {'dandelion', 'rose', 'tulip'} 
    colours = {'blue', 'yellow', 'green', 'red', 'pink', 'orange'}
    if s in colours: rtr=-3
    elif s in dogs: rtr=-2
    elif s in flowers: rtr=-1
    else: rtr=0   # this puts words not found at end of string
    return rtr 

s='husky tulip red orange'

>>> ' '.join(sorted(s.split(), key=ref))
red orange husky tulip

更多的Pythony(更容易扩展)是这样做的:

def ref(s):
    dogs = {'husky', 'chihuahua', 'labrador', 'beagle'} 
    flowers = {'dandelion', 'rose', 'tulip'} 
    colours = {'blue', 'yellow', 'green', 'red', 'pink', 'orange'}
    key_t=(colours, dogs, flowers)
    try: 
        return next(i for i, v in enumerate(key_t) if s in v)
    except StopIteration:
        return -1. # this puts words not found at beginning of string
    # or use the default argument version of next:
    # return next((i for i, v in enumerate(key_t) if s in v), -1)

并以相同的方式使用该键功能

您还可以通过使用chain将集合链接到一个iterable中来迭代集合:

>>> from itertools import chain
>>> [e for e in chain(colours,dogs,flowers) if e in s.split()]
['orange', 'red', 'husky', 'tulip']

哪个更快或更好取决于字符串的大小和集合的大小。另外,如果您想进行二次排序(例如单个类别中的词典排序),则需要使用sorted方法

试试这个

#Define all the categories
dogs = ['husky', 'chihuahua', 'labrador', 'beagle']
flowers = ['dandelion', 'rose', 'tulip']
colours = ['blue', 'yellow', 'green', 'red', 'pink', 'orange']

#The Input String
outOfOrder = "husky tulip red orange"

#Split up the string into an array which each word seperated
outOfOrderArray = outOfOrder.split()

#Array to hold all words of each category
orderedArray = [[], [], [], []]

#loop through all the words in the array
for word in outOfOrderArray:

    #Check if the word is in each category.
    if word in dogs:
        orderedArray[2].append(word)
    elif word in flowers:
        orderedArray[1].append(word)
    elif word in colours:
        orderedArray[0].append(word)

    #If its not in the array, do whatever you want with it. I jsut stuck them at the end.
    else:
        orderedArray[3].append(word)

orderedString = ""

#Combine all the words in ordered Array to create a final string
for category in orderedArray:
    for word in category:
        orderedString = orderedString + word + " "

print(orderedString)

你可以用关键字{{CD1}}将花朵向后推,并用键{^ }将颜色拉到前面(并且所有其他东西都将在中间使用键{^ }):

>>> ' '.join(sorted(s.split(), key=lambda w: (w in flowers) - (w in colours)))
'red husky orange tulip'
请注意,“橙色”不属于你的任何种类,这就是为什么它和“哈士奇”一起出现在中间。

一种更普遍的方法是将花推得最远,将狗推得较少,将颜色推得最少:

>>> ' '.join(sorted(s.split(), key=lambda w: (w in flowers, w in dogs, w in colours)))
'orange red husky tulip'

相关问题 更多 >