Find partial keywords in python list - python

x = 'a'
list = ['ab','cd','a']
if x in list:
print(list.index(x))
Here I try to find all the values in list which contains 'a'. But with the 'in' method I can only find the value which is 'a' rather than contain 'a',like 'ab'. Are there any efficient ways to do so? Thanks

Requires a list comprehension to get it done -
x = 'a'
list_ = ['ab','cd','a']
filtered_list = [elem for elem in list_ if x in elem]
print(filtered_list)
Output -
['ab', 'a']

You can use a simple for loop for this. Loop through the list and for each element in the list check whether your x is a substring of that element with in. If it is true display that element.
You can do it in python like this..
x = 'a'
list = ['ab','cd','a']
for element in list:
if x in element:
print(element)
Output
ab
a

Related

Find Numbers in a List Consisting of Strings and Convert them to Floats

I'm trying to do an exercise where I have a list:
list_1 = ['chocolate;1.20', 'book;5.50', 'hat;3.25']
And I have to make a second list out of it that looks like this:
list_2 = [['chocolate', 1.20], ['book', 5.50], ['hat', 3.25]]
In the second list the numbers have to be floats and without the ' '
So far I've come up with this code:
for item in list_1:
list_2.append(item.split(';'))
The output looks about right:
[['chocolate', '1.20'], ['book', '5.50'], ['hat', '3.25']]
But how do I convert those numbers into floats and remove the double quotes?
I tried:
for item in list_2:
if(item.isdigit()):
item = float(item)
Getting:
AttributeError: 'list' object has no attribute 'isdigit'
list_1 = ['chocolate;1.20', 'book;5.50', 'hat;3.25']
list_2 = [x.split(';') for x in list_1]
list_3 = [[x[0], float(x[1])] for x in list_2]
item is a list like ['chocolate', '1.20']. You should be calling isdigit() on item[1], not item. But isdigit() isn't true when the string contains ., so that won't work anyway.
Put the split string in a variable, then call float() on the second element.
for item in list_1:
words = item.split(';')
words[1] = float(words[1])
list_2.append(words)
I don't know if this helpful for you.
But,I think using function is better than just using simple for loop
Just try it.
def list_map(string_val,float_val):
return [string_val,float_val]
def string_spliter(list_1):
string_form=[]
float_form=[]
for string in list_1:
str_val,float_val=string.split(";")
string_form.append(str_val)
float_form.append(float_val)
return string_form,float_form
list_1 = ['chocolate;1.20', 'book;5.50', 'hat;3.25']
string_form,float_form=string_spliter(list_1)
float_form=list(map(float,float_form))
output=list(map(list_map,string_form,float_form))
print(output)
Your way of creating list_2 is fine. To then make your new list, you can use final_list = [[i[0], float(i[1])] for i in list_2]
You could also do it in the for loop like this:
for item in list_1:
split_item = item.split(';')
list_2.append([split_item[0], float(split_item[1])])
This can be achieved in two lines of code using list comprehensions.
list_1 = ['chocolate;1.20', 'book;5.50', 'hat;3.25']
list_2 = [[a, float(b)] for x in list_1 for a, b in [x.split(';', 1)]]
The second "dimension" to the list comprehension generates a list with a single sublist. This lets us essentially save the result of splitting each item and then bind those two items to a and b to make using them cleaner that having to specify indexes.
Note: by calling split with a second argument of 1 we ensure the string is only split at most once.
You can use a function map to convert each value.
def modify_element(el):
name, value = el.split(';')
return [name, float(value)]
list_1 = ['chocolate;1.20', 'book;5.50', 'hat;3.25']
result = list(map(modify_element, list_1))
For a problem like this you can initialize two variables for the result of calling the split function and then append a list of both values and call the builtin float function on the second value.
array = []
for i in a_list:
string, number = i.split(";")
array.append([string, float(number)])
print(array)

How do I check if some elements of sublist exists in list (Python)?

I have a list, for example like this below:
list=[['a',0,1200],['b',1,900],['c',2,500],['a',1,200]]
and I need to check if these sub-lists contain the same element, for this example suppose to find the first element of each sub-list, so It will be found that ['a',1,200] was the same with ['a',0,1200],
because their first element are 'a'
So how do I find out all the duplicated sub-lists?
list[0] in list [1]
(in your case is False.)
for exemple you can check if first list in sec list.
if you want to check spcific (compere letter)
you can use to "extract" the list:
for x in list:
print(x)
and if you want to compare spcific the fisrt letter, but not all the sub-list.
counter = 0
for x in list:
for i in list:
if i != x and i[0] in x[0]:
counter += 0.5
(sorry about my english)

Remove item from a list element?

This may seem odd, but I am trying to remove a part of an item contained in a list. Basically, I am trying to remove a specific character from multiple list elements. For example
list = ['c1','c2','c3','d1','s1']
list.remove('c')
I know that doing that wouldn't work, but is there any way to remove the "c"s in the list, and only the "c"s in Python 3?
lst = [s.replace('c','') for s in lst]
# ['1','2','3','d1','s1']
List comprehensions are your friend. Also note the "list" is a keyword in Python, so I highly recommend you do not use it as a variable name.
Use list comprehensions,
list = ['c1','c2','c3','d1','s1']
list_ = [ x for x in list if "c" not in x ] # removes elements which has "c"
print list_ # ['d1', 's1']
list1 = ['c1','c2','c3','d1','d2']
list2 = []
for i in range (len(list1)):
if 'c' not in list1[i]:
list2.append(list1[i])
print (list2) #['d1', 'd2']
and also this link may helpful
Link one

How can I check if a list exist in a dictionary of lists in the same order

Say I have a dictionary of lists,
C = {}
li = []
li.append(x)
C[ind] = li
And I want to check if another list is a member of this dictionary.
for s in C.values():
s.append(w)
Python checks it for any occurrences of the values in s and the dictionary values. But I want to check if any of the lists in the dictionary is identical to the given list.
How can I do it?
Use any for a list of lists:
d = {1 : [1,2,3], 2: [2,1]}
lsts = [[1,2],[2,1]]
print(any(x in d.values() for x in lsts))
True
d = {1:[1,2,3],2:[1,2]}
lsts = [[3,2,1],[2,1]]
print(any(x in d.values() for x in lsts))
False
Or in for a single list:
lst = [1,2]
lst in d.itervalues()
Python will compare each element of both lists so they will have to have the same order to be equal, even if they have the same elements inside the order must also be the same so a simple comparison will do what you want.
in does the trick perfectly, because it does a comparison with each element behind the scenes, so it works even for mutable elements:
lst in d.values()

How to get a character from a list of tuples

I have a list of tuples like
[('EVTTIMESTAMP','timestamp'),('SUBSYTEMID','int'),('VRR ','string')]
How can I get the value EVTTIMESTAMP?
Generally you can loop through your list.
For example:
myList = [('EVTTIMESTAMP','timestamp'),('SUBSYTEMID','int'),('VRR ','string')] ;
for x in range(0,len(myList)):
print(myList[x][0])
This will print:
EVTTIMESTAMP
SUBSYTEMID
VRR
Inside the loop you can put some logic to compare each element with the one you want to perform an operation on and only return the match.
For example:
for x in range(0,len(myList)):
if myList[x][0] == "EVTTIMESTAMP":
b = myList[x][0]
##do something with b
If you know the exact position of the item, then you can just call it like:
b = myList[0][0] etc...
For example:
print(myList[0][0]) will print: EVTTIMESTAMP
Hope this helps
for getting all the 2nd value of the tuples you can use
a = [('EVTTIMESTAMP','timestamp'),('SUBSYTEMID','int'),('VRR ','string')]
[x[1] for x in a]
for getting specific value of "EVTTIMESTAMP" u can use if condition
[x[1] for x in a if x[0] == 'EVTTIMESTAMP']

Categories

Resources