How to get a character from a list of tuples - python

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']

Related

How to access values from nested list using for loop

I have one of problem statement
List =[[[1,2],[3,4]]]
And i want 1st index from both nested list in list a and 2nd index from both nested list in list b using for loop and if else not using append()
Like:
a = [1,3]
b = [2,4]
How about this:
l = [[[1,2],[3,4]]]
a = []
b = []
for x in l[0]:
a.append(x[0])
b.append(x[1])
There is more pythonic way to do this, but code above is written to make it understandable.
If you write
a=[List[0][0][0], List[0][1][0]]
b=[List[0][0][1], List[0][1][1]]
You get what you want. You can define it in a loop, of course
l = [[[1,2],[3,4]]]
a = [x[0] for x in l[0]]
b = [x[1] for x in l[0]]
List comprehensions are essentially for loops in lists they pretty much read like a sentence:
do x FOR x in OTHER_LIST (and wrap that in a list)

How to change the index of an element in a list/array to another position/index without deleting/changing the original element and its value

For example lets say I have a list as below,
list = ['list4','this1','my3','is2'] or [1,6,'one','six']
So now I want to change the index of each element to match the number or make sense as I see fit (needn't be number) like so, (basically change the index of the element to wherever I want)
list = ['this1','is2','my3','list4'] or ['one',1,'six',6]
how do I do this whether there be numbers or not ?
Please help, Thanks in advance.
If you don't wanna use regex and learn it's mini language use this simpler method:
list1 = ['list4','this1', 'he5re', 'my3','is2']
def mySort(string):
if any(char.isdigit() for char in string): #Check if theres a number in the string
return [float(char) for char in string if char.isdigit()][0] #Return list of numbers, and return the first one (we are expecting only one number in the string)
list1.sort(key = mySort)
print(list1)
Inspired by this answer: https://stackoverflow.com/a/4289557/11101156
For the first one, it is easy:
>>> lst = ['list4','this1','my3','is2']
>>> lst = sorted(lst, key=lambda x:int(x[-1]))
>>> lst
['this1', 'is2', 'my3', 'list4']
But this assumes each item is string, and the last character of each item is numeric. Also it works as long as the numeric parts in each item is single digit. Otherwise it breaks. For the second one, you need to define "how you see it fit", in order to sort it in a logic.
If there are multiple numeric characters:
>>> import re
>>> lst = ['lis22t4','th2is21','my3','is2']
>>> sorted(lst, key=lambda x:int(re.search(r'\d+$', x).group(0)))
['is2', 'my3', 'list4', 'this21']
# or,
>>> ['is2', 'my3', 'lis22t4', 'th2is21']
But you can always do:
>>> lst = [1,6,'one','six']
>>> lst = [lst[2], lst[0], lst[3], lst[1]]
>>> lst
['one', 1, 'six', 6]
Also, don't use python built-ins as variable names. list is a bad variable name.
If you just want to move element in position 'y' to position 'x' of a list, you can try this one-liner, using pop and insert:
lst.insert(x, lst.pop(y))
If you know the order how you want to change indexes you can write simple code:
old_list= ['list4','this1','my3','is2']
order = [1, 3, 2, 0]
new_list = [old_list[idx] for idx in order]
If you can write your logic as a function, you can use sorted() and pass your function name as a key:
old_list= ['list4','this1','my3','is2']
def extract_number(string):
digits = ''.join([c for c in string if c.isdigit()])
return int(digits)
new_list = sorted(old_list, key = extract_number)
This case list is sorted by number, which is constructed by combining digits found in a string.
a = [1,2,3,4]
def rep(s, l, ab):
id = l.index(s)
q = s
del(l[id])
l.insert(ab, q)
return l
l = rep(a[0], a, 2)
print(l)
Hope you like this
Its much simpler

How to convert tuple to list with float and string values

I have a list of tuples like this:
tuple_list = [(['MATH120'], 3.665, 0.4737615433949868), (['GER'], 3.4566666666666666, 0.3967146329542181), (['FREE'], 3.415636363636364, 0.450256863026264), ([''], 0.041607963246554365, 0.38832820111766464)]
and what I want to do is convert this to:
result = [['MATH120', 3.665, 0.4737615433949868],['GER', 3.4566666666666666, 0.3967146329542181],['FREE', 3.415636363636364, 0.450256863026264]]
meaning that I want to convert it into a list of 3 pairs and delete the whole tuple if the list it has inside has only elements that are empty and delete also the empty strings that might exist in the tuple for example if it was like this:
tuple_list = [(['MATH120',''], 3.665, 0.4737615433949868), (['GER','',''], 3.4566666666666666, 0.3967146329542181), (['FREE'], 3.415636363636364, 0.450256863026264), ([''], 0.041607963246554365, 0.38832820111766464)]
I want it to turn to the same as previous:
result = [['MATH120', 3.665, 0.4737615433949868],['GER', 3.4566666666666666, 0.3967146329542181],['FREE', 3.415636363636364, 0.450256863026264]]
I tried doing this in order to put them just in list:
result= [list(map(list, l)) for l in tuple_list]
but I kept on getting error because of the float values:
TypeError: 'float' object is not iterable
If your data is always regular like that, and you only want the first element in the inner lists, then simply:
>>> [[x, y, z] for [x, *_], y, z in data]
[['MATH120', 3.665, 0.4737615433949868], ['GER', 3.4566666666666666, 0.3967146329542181], ['FREE', 3.415636363636364, 0.450256863026264], ['', 0.041607963246554365, 0.38832820111766464]]
FINAL EDIT:
Since you've clarified that they are empty strings, we can do something a little nicer:
>>> [ [*filter(None, lst), a, b] for lst, a, b in data if any(lst) ]
[['MATH120', 3.665, 0.4737615433949868], ['GER', 3.4566666666666666, 0.3967146329542181], ['FREE', 3.415636363636364, 0.450256863026264]]
>>>
Which I actually think is quite nicely declarative
result= [ [e for e in l if e] + list(t) for l, *t in tuple_list if any(l) ]
[e in t[0] if e] removes empty strings from a sublist; then the remaining elements of the tuple are appended; but if there are no non-empty elements in a list (any(t[0]) is False) then this tuple is skipped.
The reason you get this error is because when you call map(list, l), l refers to an inner tuple (E.G. (['MATH120'], 3.665, 0.4737615433949868)), and those floats cannot be converted to a list directly. I recommend doing something like the following:
for listIndex in range(tuple_list):
tuple_list[listIndex] = list(tuple_list[listIndex]) # Converts inner tuples to list
for element in inner_tuple:
if isinstance(element, list): # checks if element inside tuple is list
#do logic on list that you need
If your first element is always a list in your tuple, just account for it in more hardcoded way. It will only work with data in same format as examples you presented, list(tuple(list(...), ...), ...)
result_list = []
for x in tuple_list:
temp_tuple = []
if (len(x[0]) == 1 and x[0][0] == '') or len(x[0]) == 0:
continue
for y in x[0]:
if y == '':
continue
temp_tuple.append(y)
for y in range(1, len(x)):
temp_tuple.append(x[y])
result_list.append(temp_tuple)
I tested and result on examples and output was like you asked.
This solution is not one-line solution like other answers. But I personally prefer to avoid one-line loops in python if I can. That makes it easier for me to read it.
You just had one level too much. Use this:
result = [list(x) for x in tuple_list]
or
result = list(map(list, tuple_list))

Find partial keywords in python list

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

Comprehension list on nested list (list of lists)

It is allowed the use of a comprehension list on a "list of lists"?
I would like to extract a list from a nested list.
I did try this:
def main():
a = ['1','2','3']
b = ['4','5','6']
c = ['7','8','9']
board = [a,b,c]
y = [x for x in board[1][i] if i in range(0,3)]
print y
but I get "NameError: name 'i' is not defined".
I'm using the wrong syntax or nested list cannot be used like this?
Thanks a lot!
Nesting loops in list comprehensions work the same way as nesting regular for loops, one inside the other:
y = [x for i in range(3) for x in board[1][i]]
but in this case, just selecting board[1][:] would be easier and give you the same result; a copy of the middle row.
If you need to apply an expression to each column in that row, then just loop over board[1] directly:
y = [foobar(c) for c in board[1]]

Categories

Resources