I have a named tuple with values [x,y].
Both fields will hold strings.
My problem is ,I want to match the contents of the 'x' field and access the 'y' field of that index.
name_array_tuple_list
is the name of the list which holds the named tuples.
So far I have got this
print([x[0] for x in name_array_tuple_list].index('SNVT'))
Which prints the index of the matched value.
My question is how to access the y value of lets say the index 3.
You were very close. Try this:
print([point.y for point in name_array_tuple_list if point.x == 'SNVT'])
Interpret the code as follows:
print
a list of
y field contents
for every named tuple in a list
but only if the named tuple's x field matches SVNT
Related
I am comparing two list:
gp_yu = set(agencys_sp2).intersection(gp_list_t)
the output is in braces like this {900}. What can i do to remove the braces
You can obtain an element from an iterable iterable (a set is an iterable, but lists, dictionaries, etc. are iterables as well) with:
element = next(iter(iterable))
In case the iterable contains two or more elements, it will return the first element (a set has no really a "first" element in the sense that the order can very over time, but it will return an element).
In case the iterable contains no elements at all (an empty set, list, tuple, dictionary, etc.), then it will raise a StopIteration error. You can however let the expression return a default value with:
element = next(iter(iterable), default)
So in case iterable contains one or more elements, the "first" element is returned, in case it is empty, it will return default.
Probably you mean some like how to get your set as a string, so just use join function.
Some like this ', '.join(gp_yu).
Check this topic for more information:
Python: how to join entries in a set into one string?
I have a python dictionary of the type
Mutual={'A':[[1],[2],[],[]],'B':[[1],[],[],[]]}
I want to access the elements for key 'A'.
I tried this:
count=0
for z in range(2):
print Mutual["A"][z][count]
count+=1
I am getting the following error
IndexError: list index out of range
Can anyone suggest why is it so. Must be some silly mistake which I am unable to catch.
When you run the first iteration, Mutual["A"][z][count] returns 1. On the next iteration Mutual["A"][z][count] is supposed to be the second element in the list [2] (z is 1 and count is 1 as well) which does not exist. That is why you get an IndexError: list index out of range error.
A suggested modification to your code could be:
listA = Mutual["A"]
for z in range(len(listA)):
for w in range(len(listA[z])):
print listA[z][w]
This way, if the inner lists are of size zero the inner loop will not be executed and therefore, you will not try to access an out of bounds index.
It is usual in python to iterate the actual elements vs. using range() and indexes:
for z in Mutual['A']:
for count in z:
print count
I feel like this question should have been asked before but I may be too inexperienced in Python to either (1) locate the answer or (2) understand the answer.
I have a dictionary that contains lists. Each key has three values associated with it inside of a list. Since the values are in a list, I assume that means they are indexed. I know that dictionary keys are unordered and normally values are as well. However, since the values are in a list they should be ordered, correct?
I want to write a for loop that will store the first value within each key to a new list. Or, alternatively, I just want to know how to access values in a dictionary!
I tried the following:
name = dictionary of lists
for key, values in name.iteritems():
xCoord = key[1]
print xCoord
However, I get the error: "IndexError: string index out of range." What would be the way to call/retrieve the first value associated with each key? Thank you!
EDIT: I created the dictionary with the following.
inputCSV = r"G:\REDIRECT\GRP\Test\Workspace\GRPNOV16A.csv"
name = {}
with open((inputCSV),'rb') as offenseFile:
read = csv.DictReader(offenseFile)
for row in read:
if row['Defendant'] not in name:
name[row['Defendant']] = []
name[row['Defendant']].append((row['X - Offense'],row['Y - Offense'],row['GRP Status']))
offenseFile.close
EDIT 2: For anyone in the future who is inexperienced and needs a similar question answered. The dictionary code above was creating a tuple within a list within the dictionary. As a result, to access the tuple I had to do:
for key, values in name.iteritems():
xCoord = key[0][1]
print xCoord
Since the values are in a list, shouldn't this be more like it?
for key, values in name.iteritems():
xCoord = values[1]
print xCoord
I want to cast dictionary and log it.
dict:(enlist`code)!(enlist`B10005)
when I do
type value dict / 11h
but the key looks like ,code
when I do
type string value dict / 0h
I am not sure why.
I want to concatenate with strings and log it. So it will be something like:
"The constraint is ",string key dict
But it did not work. The constraint will be like each letter for each line. How I can cast the dictionary so I can concatenate and log it.
Have a look at http://code.kx.com/q/ref/dotq/#qs-plain-text for logging arbitrary kdb+ datatypes.
q)show dict:`key1`key2!`value1`value2
key1| value1
key2| value2
q).Q.s dict
"key1| value1\nkey2| value2\n"
There are several things are going on here.
dict has one key/value pair only but this fact doesn't affect how key and value behave: they return all keys and values. This is why type value dict is 11h which is a list of symbols. For exact same reason key dict is ,`code where comma means enlist: key dict is a list of symbols which (in your particular example) happens to have just one symbol `code.
string applied to a list of symbols converts every element of that list to a string and returns a list of strings
a string in q is a simple list of characters (see http://code.kx.com/wiki/Tutorials/Lists for more on simple and mixed lists)
when you join a simple list of characters "The constraint is " with a list of strings, i.e. a list of lists of characters a result cannot be represented as a simple list anymore and becomes a generic list. This is why q converts "The constraint is " (simple list) to ("T";"h";"e",...) (generic list) before joining and you q starts displaying each character on a separate line.
I hope you understand now what's happening. Depending on your needs you can fix your code like this:
"The constraint is ",first string key dict / displays the first key
"The constraint is ",", "sv string key dict / displays all keys separated by commas
Hope this helps.
if you are looking something for nice logging, something like this should help you(and is generic)
iterate through values, and convert to strings
s:{$[all 10h=type each x;","sv x;0h~t:type x;.z.s each x;10h~t;x;"," sv $[t<0;enlist#;(::)]string x]}/
string manipulation
fs:{((,)string[count x]," keys were passed")," " sv/:("Key:";"and the values for it were:"),'/:flip (string key#;value)#\:s each x}
examples
d:((,)`a)!(,)`a
d2:`a`b!("he";"lo")
d3:`a`b!((10 20);("he";"sss";"ssss"))
results and execution
fs each (d;d2;d3)
you can tailor obviously to your exact needs - this is not tested for complex dict values
I am writing a program to create a list from a spreadsheet based on a position value in another cell. So my code looks like
for j in xrange(1,13):
for sheet in wb.sheets():
for i in xrange(1,12*15):
team=sheet.cell(i,0)
position=sheet.cell(i,2)
games=sheet.cell(i,23)
if re.match(owner[j], str(team.value)) and (not re.findall('Defense' or 'K,' or 'KFG' or 'KKO', str(position.value))):
try:
list.append(int(games.value))
except ValueError:
list.append(0)
else:
pass
print list
list=[]
So the goal of this is to append to a list when a row matches owner in the first column, and not Defense K, KFG KKO in the position column.
Unfortunately, the values for K, KFG and KKO all show
up in my lists, but the Defense values properly do not. How can I
ensure the other filtering criteria are met?
As a side note, these positions are in amongst other bits of text so
the search() is used here instead of match().
"Defense" is a 'truthy' value, so the result of:
'Defense' or 'K,' or 'KFG' or 'KKO'
is 'Defense'.
Therefore, the condition you have is no different from:
re.match(owner[j], str(team.value)) and (not re.findall('Defense', str(position.value)))
If you want alternatives in a regex, use | in the pattern:
re.match(owner[j], str(team.value)) and (not re.findall('Defense|K,|KFG|KKO', str(position.value)))