Home > Blockchain >  How can I handle different versions of word TV in list of lists?
How can I handle different versions of word TV in list of lists?

Time:07-25

While pulling some amenities data from the site insideairbnb,I noticed there were different types of TVs.

tv_list = [["TV","water","Gas","wifi"], ["HDTV","shower"],["50//TV",'sauna'],["TV with Roku","a bunch of stuff"],["Cable TV"],["suana","bathtub","Direct TV","couch","spinach"]]

What I want to do is change all strings with TV to TV. Example "HDTV" would become TV. "TV with Roku" would become "TV". But I cannot account for all the different types. Can someone please assist?

for element in tv_list:
    if "TV" or "HDTV" or "Cable TV" in element:
        for i in range(len(element)):
            if "TV"in element[i]:
                element[i] ="TV"

CodePudding user response:

You can check in each element of list is existing TV or not, If TV is existing insert TV instead of all words.

for row, lst in enumerate(tv_list):
    for col, item in enumerate(lst):
        if 'TV' in item:
            tv_list[row][col] = 'TV'
print(tv_list)

OR with list comprehensions:

res = [['TV' if 'TV' in item else item for item in lst] for lst in tv_list ]

[
    ['TV', 'water', 'Gas', 'wifi'], 
    ['TV', 'shower'], 
    ['TV', 'sauna'], 
    ['TV', 'a bunch of stuff'], 
    ['TV'], 
    ['suana', 'bathtub', 'TV', 'couch', 'spinach']
]

CodePudding user response:

"TV" in element, should account for all the possibilities you specified above. But you should still be aware of exceptions where "TV" is not inside the TV-Data-String

This one here could be one possibility, but Why do you check first if there is any TV inside.... That's like checking two times one thing

for element in tv_list:
    if  any( map(lambda x: "TV" in x, element)):
        for i in range(len(element)):
            if "TV"in element[i]:
                element[i] ="TV"

this one here should be more efficient

for element in tv_list:
        for i in range(len(element)):
            if "TV" in element[i]:
                element[i] ="TV"

CodePudding user response:

Yes, you can do so with a simple list comprehension. This is given in another answer, but with the slight improvements that it is not a nested comprehension, which can be a bit more clear, and it matches even lower case instances of "tv".

updated = []
for ammenities in tv_list:
    updated.append(["TV" if "tv" in a.lower() else a for a in ammenities])

This, if printed gives:

[
    ["TV", "water", "Gas", "wifi"],
    ["TV", "shower"],
    ["TV", "sauna"],
    ["TV", "a bunch of stuff"],
    ["TV"],
    ["suana", "bathtub", "TV", "couch", "spinach"],
]

You may also want to check for "television":

updated = []
for ammenities in tv_list:
    updated.append(
        [
            "TV" if "tv" in a.lower() or "television" in a.lower() else a
            for a in ammenities
        ]
    )
  • Related