List of List- delete characters - python-3.x

I have a huge list like
list = [["a", "bfgf", "c%2"], ["b", "hhj", "kkkk", "f%2"]]
I want to remove %2 end of every last item in lists of list.
I tried
list = [[item[-1].replace('%2', '') for item in lst] for lst in list]
and it did not work

Your way does not work because you are not changing the value in place. Your statement simply takes a copy of every sub-list, stores it in lst, then changes the data in that copy, and not the actual list itself.
Try it in this way, and tell me if it works.
myList= [["a","bfgf","c%2"],["b","hhj","kkkk","f%2"]]
for i in range(len(myList)):
Last=myList[i].pop()
Last=Last.replace("%2","")
myList[i].append(Last)
print (myList)

For your nested list you can also use a nested list comprehension to remove the unwanted characters.
ini_list = [["a", "bfgf", "c%2"],["b", "hhj", "kkkk", "f%2"]]
ini_list = [[val.replace('%2', '') for val in sublist] for sublist in ini_list]
print(ini_list)
# output
[['a', 'bfgf', 'c'], ['b', 'hhj', 'kkkk', 'f']]

Related

Delete sub-list from list in python

I need to remove the sub lists from a list in Python.
For example: The main list A contains
A=[ 'a,b,c', 'd,e,f' , 'g,h,i' , 'g,l,m' , 's,l,k' , 'd,k,l', 'a,g,d' ]
I need to remove the sub lists from A which begin with the items in the following list:
B = ['g','d']
so that Final List A = [ 'a,b,c', 's,l,k' , 'a,g,d' ]
Thanks in advance
Using list comprehension:
print([x for x in A if x[0] not in ['g', 'd']])
You can do it using list comprehension and split(",").
print([e for e in A if e.split(",")[0] not in B])
Output
['a,b,c', 's,l,k', 'a,g,d']
Your output above for your approach is wrong.
2nd Element 'd,e,f' should also be removed as start element 'd' is in second list.

Remove sublist from DEEP nestedlist

I'm struggling with some NESTED LISTS.
Briefly, inside the list of lists I have some lists containing several value
biglist = [[['strings', '632'], ['otherstrings', 'hey']],[['blabla', '924'], ['histring', 'hello']]]
from this nested list, I'd like to remove the sublist in which 'hello' string appears.
I tried this:
for sub_line in big_list:
if 'hello' in sub_line:
big_list.remove(sub_line)
Now, if I print the new big_list outside the loop, I get the old list since I didn't assign the updated list to a new list. But if I assign to a new list like:
for sub_line in big_list:
if 'hello' in sub_line:
updated_list = big_list.remove(sub_line)
print(updated_list)
I get an AttributeError: 'NoneType' object has no attribute 'remove'.
So what's the problem with this?
I CANNOT use list indexing because my real list is huge and the target value is not always in the same place.
I've already check other questions but nothing is working.
Thank you all!
if you constantly have two levels of nesting (not what I would label DEEP), you could combine this answer from the dupe marking by #pault with list flattening:
biglist = [[['strings', '632'], ['otherstrings', 'hey']],[['blabla', '924'], ['histring', 'hello']]]
token = 'hello'
smalllist = [x for x in biglist if not token in [j for i in x for j in i]]
# smalllist
# Out[17]: [[['strings', '632'], ['otherstrings', 'hey']]]
Following works for me. You need to remove sub_line (not line) form the list.
big_list = [['strings', '632', 'otherstrings', 'hey'],['blabla', '924', 'histring', 'hello']]
print(big_list)
for sub_line in big_list:
if 'hello' in sub_line:
big_list.remove(sub_line)
print(big_list)
for sublist in biglist:
if 'hello' in sublist:
updated_list=biglist.remove(sublist)
print(updated_list)
The output of the above code is None because remove() does not return any value i.e, it returns None. So you should not assign return value of remove() in a list.
I think that might cause some problems whenever you will use updated_list.

reverse numbers in a list of tuples

I have some coordinate data that is lng,lat however I need it lat,lng
I have them in a list of tuples and need to switch them around:
myList = [(-87.93897686650001, 41.8493707892),
(-87.93893322819997, 41.8471652588),
(-87.9292710931, 41.8474548975),
(-87.91960917239999, 41.8477438951),
(-87.91927828050001, 41.8404034535)]
I have tried
newList = []
for i in range(len(myList)):
for c, x in reversed(list(enumerate(myList[i]))):
newList.append(x)
I get the below output, which is close
[41.8493707892,
-87.93897686650001,
41.8471652588,
-87.93893322819997,
41.8474548975,
-87.9292710931,
41.8477438951,
-87.91960917239999,
41.8404034535,
-87.91927828050001]
But I am looking for
[(41.8493707892, -87.93897686650001),
(41.8471652588, -87.93893322819997),
(41.8474548975, -87.9292710931),
(41.8477438951, -87.91960917239999),
(41.8404034535, -87.91927828050001)]
ideally i would like to do this all in the nested for-loop; but I do not care if I have to do something with the newList to group the pairs.
As always any help is appreciated.
Unless you're really attached to the nested for-loop, it's probably easiest to use this sort of list comprehension:
newlist=[i[::-1] for i in myList]
>>> newlist
[(41.8493707892, -87.93897686650001), (41.8471652588, -87.93893322819997), (41.8474548975, -87.9292710931), (41.8477438951, -87.91960917239999), (41.8404034535, -87.91927828050001)]
You can do this very easy with list comprehension.
[(b,a) for a,b in myList]

How do I validate whether input is inside list of nested lists?

i'm very new to python so please forgive me if my error is blatantly obvious.
The issue I am having is with line 15. I am struggling to check if the input value is NOT in the list "list"
All values currently entered (in and not in the list "list") will return the response "srry".
I know line 15 is at fault because if I create a separate list with no nested lists for the countries: England, French and Mandarin to be called just for line 15, the appropriate response based on input is printed as expected.
Any help would be highly appreciative.
#input
lang = str(input("Please Type in the Language you speak and press enter
('make sure you use a capital letter')"))
#list of countries
list = [["English", "english"], ["French", "french"], ["Mandarin",
"mandarin"]]
#list of responses
lls = ["Hello,", "Bonjour,", "Ni Hao"]
srry = "Sorry, but I don't speak that"
welcmsg = "Welcome to Coventry"
# check if input is not in list
if str(lang) not in list:
print(srry)
#provide appropriate response based on input
elif str(lang) in list[0]:
print(lls[0] + " " + welcmsg)
elif str(lang) in list[1]:
print(lls[1] + " " +welcmsg)
elif str(lang) in list[2]:
print(lls[2])
TLDR; change line 15 to search the list-of-lists:
# check if input is not in list
if lang not in [item for sublist in mylist for item in sublist]:
print(srry)
Details:
The problem is that "list" is a nested-list (a list-of-lists), and so when we check if the input value is not in the list, we're checking if the value is only in the outer-most level of the list, which are still lists.
Consider the following:
list of lists:
>>> mylist = [['a', 'b'], ['x', 'y']]
>>> 'x' in mylist
False
vs. a single-level, flat list:
>>> mylist = ['a', 'b', 'x', 'y']
>>> 'x' in mylist
True
To fix it we can either convert the initial list-of-lists to one "flat" list (single-level), or we'll need to search each sub-list within the "list".
Keeping the code as close to the original and only changing the line 15 list search:
# check if input is not in list
if lang not in [item for sublist in mylist for item in sublist]:
print(srry)
Also, as mentioned in the comment - consider using a different variable name for the "list" that doesn't overwrite the built-in keyword list to prevent unexpected behavior. Here I've used mylist for the "list" name.
Another thing you might consider is using str.lower() when taking user input:
>>> mylist = ["english", "french", "mandarin"]
>>> lang = str(input("language? ").lower())
language? French
>>> lang in mylist
True
The user can still use a capital-letter for the input, but it makes the input validation a bit easier to check with fewer strings to check. Just a side-tip.
Hope this helps!

Replace element of a list in python

I have list and i want to replace all the elements os the list with another elements.
Code:
list1 = ['1','1','3','4','5','2','3','4']
dict1 = {'dict1' : ['1','2','3','4','5'] ,'name':['su5','pra4','sa3','ma2','sri1']}
for x in range(len(dict1['dict1'])):
list1 = [word.replace(dict1['dict1'][x],dict1['name'][x]) for word in list1]
print(list1)
Actual Output:
['susri1', 'susri1', 'sa3', 'ma2', 'sri1', 'prama2', 'sa3', 'ma2']
Expected Output:
['su5','su5','sa3','ma2','sri1','pra4','sa3','ma2']
That's a very strange dictionary if you transform the dictionary so you can use it as a direct mapping then this is a relatively easy thing to do, e.g.:
>>> dict2 = dict(zip(dict1['dict1'], dict1['name']))
>>> [dict2[i] for i in list1]
['su5', 'su5', 'sa3', 'ma2', 'sri1', 'pra4', 'sa3', 'ma2']

Resources