Home > Mobile >  Replacing a string of list with another list?
Replacing a string of list with another list?

Time:12-28

I have two lists, and I am trying to replace words in the list of strings and I am trying to add to an empty list.

 data = ["int zt;",
    "public int w = ;",
    "public final int nu;public a(d dVar, int i, int i2);",
    "public int getScoreOrder() {int getInteger;",
    "for (int i = 0; i < this.nu; i  )",
    "{public a(d dVar, int t) {super(dVar, i);",
    "private int z = true ;if (getType() != 1) {z = false;",
    "protected int g = true;",
    "unprotected int z = true;if (getType() != 1) {z = false;",
    "public int getType) {return getInteger();",
    "int y;",
    "print (int i) {int k = b.k(parcel);"]



data_variable = ['zt', 'w', 'nu', 'i2', 'getScoreOrder', 'getInteger', 'i', 't', 'z', 'g', 'z', 'getType', 'y', 'i', 'k']
lis = []
data_variable = [*set(data_variable)]
print(type(lis))
for i in data_variable:
    for d in data:
        if i in d:
            s = d.replace(i," data_variable ")
            lis.append(s)
print(lis)

This small script is taking each item from list data_variable and checking with the each item of list data and if it contains item of data_variable, it just replaces it with "data_variable". And appending it to the empty list (lis).

There are 12 items in a list (data) and my script appends 48 items in list (lis). In fact list (lis) should contain 12 items.

Thank you so much in advance.

CodePudding user response:

I think there are several problems:

  • You should loop over the 'data' list first
  • You should append the new element only after you have done all replacements
  • The tricky part is that you want to replace word that are in fact letter. For example your replace function will replace every 'i' by 'data_variable'. You only want to do that if there is a space before of after the letter 'i', otherwise a word like 'public' will become 'publdata_variablec'. Maybe using a regular expression would help (https://docs.python.org/3/library/re.html), or you can just have ' i' and 'i ' in your data_variable list.

Something last this should work:

    result = []
    data_variable = ['zt', 'nu', 'i2', 'getScoreOrder', 'getInteger',  'getType','i ', ' i']
    data_variable = [*set(data_variable)]
    for d in data:
        for i in data_variable:
            d = d.replace(i," data_variable ")
        result.append(d)

    print(result)
    print(len(result))

Also to remove duplicate I would just use:

    data_variable = list(set(['zt', 'nu', 'i2', 'getScoreOrder', 'getInteger',  'getType','i ', ' i']))
  • Related