In python 3, I am trying to create an array of elements, where each element consists of two values. These values are not really key-value pairs because they are equally related to each other, meaning value 1 could be the key for value two, just as value two could be the key to value one and so I didn't think a dictionary was appropriate.
my_list = [ (VALUE1, OFFSET1), (VALUE2, OFFSET2) ]
def printList(list):
for item in list:
print(item)
How could I collect the VALUE and OFFSET "values" separately? Such as
theValue = list[0].VALUE
theOffset = list[0].OFFSET
I'm thinking an array of structs perhaps?
You can use zip, which transposes the list and collects elements at the same position to one element in the result:
value, offset = zip(*my_list)
value
#('VALUE1', 'VALUE2')
offset
#('OFFSET1', 'OFFSET2')
def printList(my_list):
for item in my_list:
print('Value ', item[0])
print('Offset ', item[1])
The for loop iterates through my_list. Each element in the loop is received as tuple like (VALUE, OFFSET) in the variable item. So item[0] is VALUE and item[1] is OFFSET. And we print it.
I'll do this like:
my_list = [ ("VALUE1", "OFFSET1"), ("VALUE2", "OFFSET2") ]
def printList(my_llst):
values = []
ofts = []
for item in my_llst:
values.append(item[0])
ofts.append(item[1])
return (values,ofts)
(['VALUE1', 'VALUE2'], ['OFFSET1', 'OFFSET2'])
Since you have a list of tuples, instead of:
theValue = list[0].VALUE
theOffset = list[0].OFFSET
You can use:
theValue = list[0][0]
theOffset = list[0][1]
So in your for-loop:
def printList(list):
for item in list:
print('VALUE: {}'.format(item[0]))
print('OFFSET: {}'.format(item[1]))
If you want to get all values in list and offsets in a separate list, you can use list-comprehension:
values = [x[0] for x in list]
offsets = [x[1] for x in list]
One more important thing, AVOID using built-in functions like list as variables, use something else instead.
Try using a list comprehension
theValue = [value[0] for value in my_list]
theOffset = [offset[0] for value in offset]
I think namedtuple can help you.
from collections import namedtuple
Element = namedtuple("Element", ["value", "offset"])
element_list = []
for value, offset in my_list:
element_list.append(Element(value, offset))
for element in element_list:
print element.value, element.offset
If you want to get all values and offsets separately, you can use numpy to transform my_list to numpy.array which is a 2d array.
import numpy as np
2d_array = np.array(my_list)
values = 2d_array[:, 0]
offsets = 2d_array[:, 1]
Related
I have a Json array which has key value pairs. I want to get value of a particular key in the list. I don't know at what position the key will be in the array so I cant use the index in the array.
How can I get this please? I have tried something like below code to get value of 'filterB' which is 'val1' but no luck. Thanks.
import json
x = '{"filters":[{"filterA":"All"},{"filterB":"val1"}]}'
y = json.loads(x)
w = y['filters']['filterB']
print (w)
w = y['filters']['filterB'] doesn't work because y['filters'] is a list and not dict.
The answer to your question depends on how you want to handle the case of multiple dictionaries inside filters list that have filterB key.
import json
x = '{"filters":[{"filterA":"All"},{"filterB":"val1"}]}'
y = json.loads(x)
# all filterB values
filter_b_values = [x['filterB'] for x in y['filters'] if 'filterB' in x.keys()]
# take first filterB value or None if no values
w = filter_b_values[0] if filter_b_values else None
The source of your data (json) has nothing to do with what you want, which is to find the dictionary in y['filters'] that contains a key called filterB. To do this, you need to iterate over the list and look for the item that fulfils this condition.
w = None
for item in y['filters']:
if 'filterB' in item:
w = item['filterB']
break
print(w) # val1
Alternatively, you could join all dictionaries into a single dictionary and use that like you originally tried
all_dict = dict()
for item in y['filters']:
all_dict.update(item)
# Replace the list of dicts with the dict
y['filters'] = all_dict
w = y['filters']['filterB']
print(w) # val1
If you have multiple dictionaries in the list that fulfil this condition and you want w to be a list of all these values, you could do:
y = {"filters":[{"filterA":"All"},{"filterB":"val1"},{"filterB":"val2"}]}
all_w = list()
for item in y['filters']:
if 'filterB' in item:
all_w.append(item['filterB'])
Or, as a list-comprehension:
all_w = [item['filterB'] for item in y['filters'] if 'filterB' in item]
print(all_w) # ['val1', 'val2']
Note that a list comprehension is just syntactic sugar for an iteration that creates a list. You aren't avoiding any looping by writing a regular loop as a list comprehension
I have a list of lists in python of the form
A=[[1,2,3,4],
[5,6,7,8],
[9,10,11,12]]
I need to get a fast way to get the row index of an element in that structure.
method(2) = 0
method(8) = 1
method(12) = 2
and so on. As always, the fastest the method the better, as my actual list of lists is quite large.
In this state, the data structure (list of lists) is not quite convenient and efficient for the queries you want to make on it. Restructure it to have it in a form:
item -> list of sublist indexes # assuming items can be present in multiple sublists
This way the lookups would be instant, by key - O(1). Let's use defaultdict(list):
>>> from collections import defaultdict
>>>
>>> d = defaultdict(list)
>>> for index, sublist in enumerate(A):
... for item in sublist:
... d[item].append(index)
...
>>> d[2]
[0]
>>> d[8]
[1]
>>> d[12]
[2]
It is very simple using next() with a generator expression:
def method(lists, value):
return next(i for i, v in enumerate(lists) if value in v)
The problem with that is that it will have an error if value does not occur. With a slightly longer function call, you can make a default of -1:
def method(lists, value):
return next((i for i,v in enumerate(lists) if value in v), -1)
Here is another way using numpy
import numpy
A = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
my_array = numpy.array(A)
numpy.where(my_array==2) ## will return both the list and the index within the list
numpy.where(my_array==12)
## As a follow up if we want only the index we can always do :
numpy.where(my_array==12)[0][0] # will return 2 , index of list
numpy.where(my_array==12)[1][0] # will return 3 , index within list
find operation in list is linear. Following is simple code in python to find an element in list of lists.
A=[[1,2,3,4],
[5,6,7,8],
[9,10,11,12]]
def method(value):
for idx, list in enumerate(A):
if value in list:
return idx
return -1
print (method(12))
I just want to get those with the index that is a multiple of two
code=[1,2,4,7,2,6,8]
ncode=[code[i] for i%2==0]
Just use this indexing method:
code[::2]
If you want the odd index
code[1::2]
Generally, this is how it works:
seq = L[start:stop:step]
seq = L[::2] # get every other item, starting with the first
seq = L[1::2] # get every other item, starting with the second
You can use list comprehensions this way :
code=[1,2,4,7,2,6,8]
print [val for i,val in enumerate(code) if i%2==0]
enumerate() returns the index and value at the index, which is stored in i and value respectively.
For more details:
list comprehension
enumerate
code = [1,2,4,7,2,6,8]
new_code = []
for i in range(0, len(code), 2): ### iterate over even indexes
new_code.append(code[i])
print new_code
I have a function h() that returns a tuple corresponding to the most common element in a list and its value from a dictionary called "Values" - so for example, if the most common element in list1 is a string "test" that occurs three times and that corresponds to Values = {"test":10}, then h(list1) = [3,10].
When two lists share the same element/frequency, I want to remove the most common element. Here is what I'm trying:
list1.remove([k for k,v in Values.items() if v == h(list1)[1]])
ValueError: list.remove(x): x not in list
How can I remove the key from a list based on its value in the Values dictionary?
Remove only expects a single element.
toremove = {k for k,v in Values.items() if v == h(list1)[1]]}
#either:
for r in toremove:
list1.remove(r)
#or (less efficient)
list1 = = [i for i in list1 if i not in toremove]
I have two Arrays:
firstArray=[['AF','AFGHANISTAN'],['AL','ALBANIA'],['DZ','ALGERIA'],['AS','AMERICAN SAMOA']]
secondArray=[[1,'AFGHANISTAN'],[3,'AMERICAN SAMOA']]
So I just need an Array which is like
thirdArray=[[1,'AF'],[3,'AS']]
I tried any(e[1] == firstArray[i][1] for e in secondArray)
It returned me True and false if second element of both array matches. but i don't know how to build the third array.
First, convert firstArray into a dict with the country as the key and abbreviation as the value, then just look up the abbreviation for each country in secondArray using a list comprehension:
abbrevDict = {country: abbrev for abbrev, country in firstArray}
thirdArray = [[key, abbrevDict[country]] for key, country in secondArray]
If you are on a Python version without dict comprehensions (2.6 and below) you can use the following to create abbrevDict:
abbrevDict = dict((country, abbrev) for abbrev, country in firstArray)
Or the more concise but less readable:
abbrevDict = dict(map(reversed, firstArray))
It is better to store them into dictionaries:
firstDictionary = {key:value for value, key in firstArray}
# in older versions of Python:
# firstDictionary = dict((key, value) for value, key in firstArray)
then you could get the 3rd array simply by dictionary look-up:
thirdArray = [[value, firstDictionary[key]] for value, key in secondArray]
You could use an interim dict as a lookup:
firstArray=[['AF','AFGHANISTAN'],['AL','ALBANIA'],['DZ','ALGERIA'],['AS','AMERICAN SAMOA']]
secondArray=[[1,'AFGHANISTAN'],[3,'AMERICAN SAMOA']]
lookup = {snd:fst for fst, snd in firstArray}
thirdArray = [[n, lookup[name]] for n, name in secondArray]
If a dictionary would do, there is a special purpose Counter dictionary for exactly this use case.
>>> from collections import Counter
>>> Counter(firstArray + secondArray)
Counter({['AF','AFGHANISTAN']: 1 ... })
Note that the arguments are reversed from what you requested, but that's easily remedied.
The standard way to match data to a key is a dictionary. You can convert firstArray to a dictionary using dict comprehension.
firstDict = {x: y for (y, x) in firstArray}
You can then iterate over your second array using list comprehension.
[[i[0], firstDict[i[1]]] for i in secondArray]
use a list comprehension:
In [119]: fa=[['AF','AFGHANISTAN'],['AL','ALBANIA'],['DZ','ALGERIA'],['AS','AMERICAN SAMOA']]
In [120]: sa=[[1,'AFGHANISTAN'],[3,'AMERICAN SAMOA']]
In [121]: [[y[0],x[0]] for x in fa for y in sa if y[1]==x[1]]
Out[121]: [[1, 'AF'], [3, 'AS']]