How to remove specific strings from a list - python

From the following list how can I remove elements ending with Text.
My expected result is a=['1,2,3,4']
My List is a=['1,2,3,4,5Text,6Text']
Should i use endswith to go about this problem?

Split on commas, then filter on strings that are only digits:
a = [','.join(v for v in a[0].split(',') if v.isdigit())]
Demo:
>>> a=['1,2,3,4,5Text,6Text']
>>> [','.join(v for v in a[0].split(',') if v.isdigit())]
['1,2,3,4']
It looks as if you really wanted to work with lists of more than one element though, at which point you could just filter:
a = ['1', '2', '3', '4', '5Text', '6Text']
a = filter(str.isdigit, a)
or, using a list comprehension (more suitable for Python 3 too):
a = ['1', '2', '3', '4', '5Text', '6Text']
a = [v for v in a if v.isdigit()]

Use str.endswith to filter out such items:
>>> a = ['1,2,3,4,5Text,6Text']
>>> [','.join(x for x in a[0].split(',') if not x.endswith('Text'))]
['1,2,3,4']
Here str.split splits the string at ',' and returns a list:
>>> a[0].split(',')
['1', '2', '3', '4', '5Text', '6Text']
Now filter out items from this list and then join them back using str.join.

try this. This works with every text you have in the end.
a=['1,2,3,4,5Text,6Text']
a = a[0].split(',')
li = []
for v in a:
try : li.append(int(v))
except : pass
print li

Related

List, Convert Str List, replace values, print new str List. Should return ['*', '2', '3', '*', '5']

can any of you help me to identify what am I doing wrong? I know this might be simple but I
am new to programming and Python. I need to return ['*', '2', '3', '*', '5']. Instead of that I am
getting much more values within the list.
Test to replace values in a List
repl_list = [1, 2, 3, 1, 5]
str_repl_list = str(repl_list)
# print('This is the list to replace: ' + str_repl_list)
# print(type(str_repl_list[0]))
new_str_list = []`enter code here`
print(new_str_list)
for item in str_repl_list:
replacement = item.replace('1', '*')
new_str_list.append(replacement)
for index, char in enumerate(new_str_list):
print(index, char) # This is to identify what information is being taken as par of the new list
when you do a str(repl_list), the outpt is a string '[1, 2, 3, 1, 5]', not a list of strings, so if you iterate through str_repl_list you will get
1
,
2
,
3
,
1
,
5
]
Instead you can avoid that step and convert each item to string inside your for loop (str(item))
repl_list = [1, 2, 3, 1, 5]
new_str_list = []
for item in repl_list:
replacement = str(item).replace('1', '*')
new_str_list.append(replacement)
>>> print(new_str_list)
>>> ['*', '2', '3', '*', '5']
you can also use list coprehension
>>> print(['*' if x == 1 else str(x) for x in repl_list])
>>> ['*', '2', '3', '*', '5']
Instead of converting each item to string, you are converting the entire list into a string. Instead try this list comprehension:
str_repl_list = [str(i) for i in str_list]
This will go through each item and convert it into a string, then store it in the new list.
since you are appending each element in the list new_str_list, to see the desired result you need to print them together, so you need to join them in a string and add all element in the string.
so to see the desired result, you just need to add all elment together
which can be done as
str_list_final = ''.join(new_str_list)

How to compare each element of multiple lists and return name of lists which are different

I am having multiple lists and I need to compare each list with one another and return the name of lists which are different. We need to consider value of elements in list irrespective of their position while comparing lists.
For example:-
Lis1=['1','2','3']
Lis2=['1','2']
Lis3=['0','1','3']
Lis4=[]
Lis5=['1','2']
Output:-
['Lis1','Lis2','Lis3','Lis4']
Thanks in advance.
Try this:
input_lists = {"Lis1": ['1', '2', '3'], "Lis2": ['1', '2'],
"Lis3": ['0', '1', '3'], "Lis4": [], "Lis5": ['1', '2']}
output_lists = {}
for k, v in input_lists.items():
if sorted(v) not in output_lists.values():
output_lists[k] = sorted(v)
unique_keys = list(output_lists.keys())
print(unique_keys) # ['Lis1', 'Lis2', 'Lis3', 'Lis4']
import itertools
Lis1=['1','2','3']
Lis2=['1','2']
Lis3=['0','1','3']
Lis4=[]
Lis5=['1','2']
k=[Lis1,Lis2,Lis3,Lis4,Lis5]
k.sort()
list(k for k,_ in itertools.groupby(k))
output
[[], ['0', '1', '3'], ['1', '2'], ['1', '2', '3']]
a simple way to implement
Lis1=['1','2','3']
Lis2=['1','2']
Lis3=['0','1','3']
Lis4=[]
Lis5=['1','2']
lis=[Lis1,Lis2,Lis3,Lis4,Lis5]
final=[]
for ele in lis:
if(ele not in final):
final.append(ele)
print(final)
with your given data you can use:
Lis1=['1','2','3']
Lis2=['1','2']
Lis3=['0','1','3']
Lis4=[]
Lis5=['1','2']
name_lis = {'Lis1': Lis1, 'Lis2': Lis2, 'Lis3': Lis3, 'Lis4': Lis4, 'Lis5': Lis5}
tmp = set()
response = []
for k, v in name_lis.items():
s = ''.join(sorted(v))
if s not in tmp:
tmp.add(s)
response.append(k)
print(response)
output:
['Lis1', 'Lis2', 'Lis3', 'Lis4']
name_lis dictionary contains the name of your list and the actual list, you are iterating over each list, and for each list, you are sorting the elements and then converting in a string, if the string was encountered before you know that the list is a duplicate if not you are adding the list to the response

max method of a list consisting of strings

I am wondering why the result is '4' if I write the following code:
lists = ['1','2','3','4']
print(max(lists))
lists.append(5)
print(max(lists))
I suppose that the max method of lists converts from str to int first and then gives me the max of ints in the first couple of lines, but this seems untrue if I try the next lines. Can anyone explain this?
Your list contains strings and you are appending an integer.
lists = ['1', '2', '3', '4', 5]
TypeError: '>' not supported between instances of 'str' and 'int'
If you had only strings or only int's max will do the comparison as the '>' operator will work. You need to convert the list to all strings or all ints.
lists = [int(x) for x in lists] #by list comprehension
>>> max(lists) # lists= [1, 2, 3, 4, 5]
>>> 5
lists = [str(x) for x in lists]
>>> max(lists) # lists = ['1', '2', '3', '4', '5']
>>> '5'
If you have not yet seen list comprehensions it's doing this but much faster and in a single line of code.
new_list = []
for x in lists:
x = int(x) #convert each individual term to integer objects
new_list.append(x)
lists = new_list
Actually, it doesn't give you TypeError it will return '4' for both cases below:
list = ['1', '2', '3', '4']
list = ['1', '2', '3', '4', 5]
because when comparing objects in python, str always > int that's why you are getting '4' as the max value because it is the highest value among the strings
here is an example to prove what I'm saying:
>print '1' > 5
True
>print '1' > '5'
False
You can try this:
lists = ['1','2','3','4']
print(max(list(map(int, lists))))
lists.append(5)
print(max(list(map(int, lists))))

How to use a dictionary to print its partner value

Not sure if the title is specific enough.
words = ['sense', 'The', 'makes', 'sentence', 'perfect', 'sense', 'now']
numbers = ['1', '2', '3', '4', '5', '6']
dictionary = dict(zip(numbers, words))
print(dictionary)
correctorder = ['2', '4', '7', '3', '5', '6']
I'm simply trying to figure out how exactly I can print specific values from the dictionary using the correctorder array so that the sentence makes sense.
You can just iterate over correctorder and get the corresponding dict value, then join the result together.
' '.join(dictionary[ele] for ele in correctorder)
This is assuming that you fix numbers to include '7' at the end.
>>> ' '.join(dictionary[ele] for ele in correctorder)
'The sentence now makes perfect sense'
What you want is this.
for i in correctorder:
print dictionary[i]," ",
Short and simple. As Mitch said, fix the 7 though.
You could use operator.itemgetter to avoid an explicit loop:
>>> from operator import itemgetter
>>> print(itemgetter(*correctorder)(dictionary))
To concatenate this simply use str.join:
>>> ' '.join(itemgetter(*correctorder)(dictionary))

How can I split a list into smaller lists?

I have a list:
lists = (['1','2','3','S','3','4','S','4','6','7'])
And I want to split the list into s smaller list everytime 'S' appears and eliminate 'S' into something like:
([['1','2','3'],['3','4],['4','6','7']])
My code:
def x (lists):
empty = ''
list = []
for x in lists:
if x == empty:
list[-1:].append(x)
else:
list.append([x])
return (list)
I tried something like this, but I am quite new to python, and Im getting nowhere. Nothing fancy please, how would I fix what I have?
Try itertools.groupby():
>>> from itertools import groupby
>>> lists = ['1','2','3','S','3','4','S','4','6','7']
>>> [list(g[1]) for g in groupby(lists, lambda i:i!='S') if g[0]]
[['1', '2', '3'], ['3', '4'], ['4', '6', '7']]
Maybe something like map(list,''.join(lists).split('S'))
Alternately, [list(s) for s in ''.join(lists).split('S'))
Well, may be funny, but this should work:
[s.split('#') for s in '#'.join(lists).split('#S#')]
Instead of the '#' any character can be used if it's unlikely to appear in lists.

Categories

Resources