替换列表中的项目

时间:2019-07-24 12:13:42

标签: python list replace

我正在尝试根据子字符串匹配替换列表中的项目

我有以下列表

x = ['D-cat', 'cat', 'C-Rabbit', 'Rabbit', 'R-rat', 'S-rat', 'L-cat']

如果有两个项目,例如D-cat和cat,我想用没有前缀的项目替换带有前缀的项目。 即D-cat必须替换为cat。同样,我要替换 所有前缀xxx和xxx。

我对使用replace的内容感到厌倦。

x = [animal.replace('D-cat','cat') for animal in x] 

预期结果:

x = ['cat', 'cat', 'Rabbit', 'Rabbit', 'R-rat', 'S-rat', 'cat']

我不确定如何对所有项目实施此操作。

我想问些建议。

编辑: 测试用例

x =['C-Rab 6-bit', 'Rab 6-bit']

预期输出:

x=['Rab 6-bit', 'Rab 6-bit']

8 个答案:

答案 0 :(得分:2)

您可以使用基本的for循环来做到这一点:

mylist = ['D-cat', 'cat', 'C-Rabbit', 'Rabbit', 'R-rat', 'S-rat', 'L-cat']

for i in range(len(mylist)):
    for j in range(len(mylist)):
        if mylist[j] in mylist[i]:
            mylist[i] = mylist[j]

print (mylist)

输出:

['cat', 'cat', 'Rabbit', 'Rabbit', 'R-rat', 'S-rat', 'cat']

编辑:测试用例

mylist = ['C-Rab 6-bit', 'Rab 6-bit']
ouput >> ['Rab 6-bit', 'Rab 6-bit']

答案 1 :(得分:2)

为避免双重循环,我将一次传递给没有前缀的哈希动物,然后替换:

#Assuming no one letter animal. 
#The condition allows for animals with '-' 
#in the name by insisting '-'  not be the second character.
#('-' in a) would not have allowed '-' in the name.
animal_set = set(a for a in x if a[1] != '-')
for i in range(len(x)):
    animal = x[i].split('-',1)[-1]
    if animal in animal_set: x[i]= animal

我认为这比坚持理解更好,并且速度对于长列表(n ^ 2与n复杂度相比)很重要。这包括在原始列表上使用in运算符。

我还要说的是,在您选择的解决方案中,正则表达式绝对没有用-在这里可以正常进行字​​符串的拆分或索引。如果您真的想要一个衬套来进行循环,则可以使用:

[a.split('-',1)[-1] if a.split('-',1)[-1] in animal_set else a for a in x] 

但是现在您必须拆分两次而不是一次,所以我反对这样做。

请注意我传递给拆分的“ 1”-这将处理多余的破折号,例如L-complex-animal,将它们拆分为“ L”和“ complex-animal”。

答案 2 :(得分:1)

您可以使用set来更快地检查列表中是否存在无前缀的动物。

x = ["D-cat", "cat", "C-Rabbit", "Rabbit", "R-rat", "S-rat", "L-cat", "C-Rab 6-bit", "Rab 6-bit"]
x_set = set(x)

processed_animals = []
for animal in x:
    no_prefix_animal = animal.split("-", 1)[-1]
    if no_prefix_animal in x_set:
        animal = no_prefix_animal

    processed_animals.append(animal)

print(processed_animals)
# ['cat', 'cat', 'Rabbit', 'Rabbit', 'R-rat', 'S-rat', 'cat', 'Rab 6-bit', 'Rab 6-bit']

答案 3 :(得分:0)

如果您确定所需的单词和前缀用连字符分隔,并且连字符没有出现在前缀或单词中,则可能可行:

 lookup_dict = {animal:True for animal in x if '-' not in animal}

 def get_word(animal):
     without_prefix = animal.split('-')[-1]
     return without_prefix if lookup_dict.get(without_prefix) else animal

 x = [get_word(animal) for animal in x]

注意:更通用的方法是使用正则表达式。这种方法虽然很具体,但是与使用正则表达式相比非常有效。

答案 4 :(得分:0)

具有简单的列表理解和<LimitValue Type="UpperWarningLimit" ...>0.17000</limitvalue>功能:

str.find

输出:

x = ['D-cat', 'cat', 'C-Rabbit', 'Rabbit', 'R-rat', 'S-rat', 'L-cat']
res = [s[s.find('-')+1:]
       if ('-' in s and s[s.find('-')+1:] in x) else s for s in x[:]]
print(res)

答案 5 :(得分:0)

对于一种衬里的风扇(不一定推荐):

x = ['D-cat', 'cat', 'C-Rabbit', 'Rabbit', 'R-rat', 'S-rat', 'L-cat']
[re.sub('\w-', '', i) if re.sub('\w-', '', i) in x else i for i in x]

# ['cat', 'cat', 'Rabbit', 'Rabbit', 'R-rat', 'S-rat', 'cat']

答案 6 :(得分:0)

使用itertools.groupby的一种解决方案:

x = ['D-cat', 'cat', 'C-Rabbit', 'Rabbit', 'R-rat', 'S-rat', 'L-cat']

from itertools import groupby

out = []
s = sorted(enumerate(x), key=lambda k: (k[1].split()[0].split('-', maxsplit=1)[-1], len(k[1])))
for v, g in groupby(s, lambda k: k[1].split()[0].split('-', maxsplit=1)[-1]):
    l = [*g]
    remove_prefix = not '-' in l[0][-1].split()[0]
    to_replace = l[0][-1]
    out.extend([(i[0],to_replace) if remove_prefix else i for i in l])

print([i[1] for i in sorted(out)])

打印:

['cat', 'cat', 'Rabbit', 'Rabbit', 'R-rat', 'S-rat', 'cat']

打印有x = ['C-Rab 6-bit', 'Rab 6-bit']的测试用例:

['Rab 6-bit', 'Rab 6-bit']

答案 7 :(得分:0)

您可以将@Override public void start(Stage primaryStage) throws Exception { String path = "charts\\DTW_sectional\\Detroit SEC 98.tif"; //String path = "charts\\javafx-documentation.tif"; FileInputStream in = new FileInputStream(path); FileChannel channel = in.getChannel(); ByteBuffer buffer = ByteBuffer.allocate((int) channel.size()); channel.read(buffer); // create JavaFX image and load into an ImageView Image image = load(buffer.array()); System.out.println("Path: " + path + "\nImage: " + image + "\n"); ImageView imageView = new ImageView(image); //Creating a Group object Group root = new Group(imageView); //Creating a scene object Scene scene = new Scene(root, 600, 500); //Setting title to the Stage primaryStage.setTitle("Loading an image"); //Adding scene to the stage primaryStage.setScene(scene); //Displaying the contents of the stage primaryStage.show(); } 用于列表理解:

pd.DataFrame([[k, v] for k, V in result.items() for v in V])

          0         1
0   76213.0   76213.0
1   76213.0   97808.0
2   76213.0     377.0
3   76213.0  106118.0
4  133185.0  133185.0
5  133185.0  132732.0

输出:

enumerate