how to use min in nested dict? - python

if I have:
a = {
(1,1): {'prev': '.', 'cur': '.', 'possible': ['2', '7', '8', '9']},
(2,2): {'prev': '.', 'cur': '.', 'possible': ['1', '3', '8']},
(3,3): {'prev': '.', 'cur': '.', 'possible': ['2', '7', '8', '9', '8']}
}
And I want to get the key that has shortest length of 'possible'.
I wrote:
b = min(a, key=lambda x: len(a[x]['possible']))
It actually works.
Is there another way I can write? I was trying to see if I can use get() in dict methods.
Thanks!

I mean, you could go:
b = min(a, key=lambda x: len(a.get(x).get('possible')))
But your solution is good itself.

Related

How to reverse multiple lists?

scores=open('scores.csv','r')
for score in scores.readlines():
score = score.strip()
rev=[]
for s in reversed(score[0:]):
rev.append(s)
print(rev)
This is my code, what I am going to do is the print reversed list from scores.csv
If I print scores at the beginning, the result is:
['0.74,0.63,0.58,0.89\n', '0.91,0.89,0.78,0.99\n', '0.43,0.35,0.34,0.45\n', '0.56,0.61,0.66,0.58\n', '0.50,0.49,0.76,0.72\n', '0.88,0.75,0.61,0.78\n']
It looks normal, and if I print score after I remove all \n in the list, the result is:
0.74,0.63,0.58,0.89
0.91,0.89,0.78,0.99
0.43,0.35,0.34,0.45
0.56,0.61,0.66,0.58
0.50,0.49,0.76,0.72
0.88,0.75,0.61,0.78
it still looks ok, but if I print at the end of the code, it shows:
['9', '8', '.', '0', ',', '8', '5', '.', '0', ',', '3', '6', '.', '0', ',', '4', '7', '.', '0']
['9', '9', '.', '0', ',', '8', '7', '.', '0', ',', '9', '8', '.', '0', ',', '1', '9', '.', '0']
['5', '4', '.', '0', ',', '4', '3', '.', '0', ',', '5', '3', '.', '0', ',', '3', '4', '.', '0']
['8', '5', '.', '0', ',', '6', '6', '.', '0', ',', '1', '6', '.', '0', ',', '6', '5', '.', '0']
['2', '7', '.', '0', ',', '6', '7', '.', '0', ',', '9', '4', '.', '0', ',', '0', '5', '.', '0']
['8', '7', '.', '0', ',', '1', '6', '.', '0', ',', '5', '7', '.', '0', ',', '8', '8', '.', '0']
looks like python converts my result from decimal to integer, but when I am trying to use float(s) to convert it back, it gives me an error. I would like to know what's wrong with my code?
In your approach, score is a string, so it's doing exactly what you tell it to: reverse the entire line character by character. You can do two things:
Use the csv module to read your CSV file (recommended), to get a list of float values, then reverse that.
Split your line on commas, then reverse that list, and finally stitch it back together. An easy way to reverse a list in Python is mylist[::-1].
For number 2, it would be something like:
score = score.strip()
temp = score.split(',')
temp_reversed = temp[::-1]
score_reversed = ','.join(temp_reversed)
always use csv module to read csv files. This module parses the data, splits according to commas, etc...
Your attempt is just reversing the line char by char. I'd rewrite it completely using csv module, which yields the tokens already split by comma (default):
import csv
with open('scores.csv','r') as scores:
cr = csv.reader(scores)
rev = []
for row in cr:
rev.append(list(reversed(row))
that doesn't convert data to float, that said, I'd replace the loop by a comprehension + float conversion
rev = [[float(x) for x in reversed(row)] for row in cr]

Change string to list when the string is already in list form

I have a list of strings:
list1=['[206,397]', '[207,397]', '[208,397]', '[209,397]', '[210,397]', '[211,399]']
and I want this output:
list1=[[206,397], [207,397], [208,397], [209,397], [210,397], [211,399]]
I tried several ways to convert the strings to lists, but I did not manage to get my desired output.
Here is what I did:
for i in list1:
i=list(i)
No change was made to list1
I tried again with another approach:
list1=['[206,397]', '[207,397]', '[208,397]', '[209,397]', '[210,397]', '[211,399]']
list2=[]
for i in list1:
list2.append(list(i))
This time the output is something like this:
[['[', '2', '0', '6', ',', '3', '9', '7', ']'], ['[', '2', '0', '7', ',', '3', '9', '7', ']'], ['[', '2', '0', '8', ',', '3', '9', '7', ']'], ['[', '2', '0', '9', ',', '3', '9', '7', ']'], ['[', '2', '1', '0', ',', '3', '9', '7', ']'], ['[', '2', '1', '1', ',', '3', '9', '9', ']']]
Can you help me with this? Thanks in advance for any help you can give
Very simple and easy to understand Python code is also this step-by-step code:
list1=['[206,397]', '[207,397]', '[208,397]', '[209,397]', '[210,397]', '[211,399]']
resultList = []
for entry in list1:
entry = entry.replace("[", "") # Trims [
entry = entry.replace("]", "") # Trims ]
number1 = int(entry.split(",")[0]) # Splits by comma and converts to integer
number2 = int(entry.split(",")[1]) # Splits by comma and converts to integer
resultList.append([number1, number2]) # Append to resultList
print(resultList)
This produces final result:
[[206, 397], [207, 397], [208, 397], [209, 397], [210, 397], [211, 399]]
JSON parsing may be appropriate as mentioned in the comments, but this would also work with the data sample you've provided. I wasn't sure if you wanted your results to be a list of lists of strings, or a list of lists of ints. Ignore the second line if the former is what you want.
list2 = [x[1:-1].split(',') for x in list1]
list3 = [[int(x) for x in y] for y in list2]
print(list3)
# [[206, 397], [207, 397], [208, 397], [209, 397], [210, 397], [211, 399]]
Edit to add: can be condensed to a one-liner if preferred:
list4 = [[int(y) for y in x[1:-1].split(',')] for x in list1]
You could use ast.literal_eval
So the code for generating the list would be : -
import ast
list1=['[206,397]', '[207,397]', '[208,397]', '[209,397]', '[210,397]', '[211,399]']
list2=[]
for i in list1:
list2.append(ast.literal_eval(i))
Note : Don't forget to import ast
Screenshot of output:-

Python 3: how to create list out of float numbers?

Anyone knows how can I solve this issue?
I have the following code.
result=[]
for i in range(len(response_i['objcontent'][0]['rowvalues'])):
lat = response_i['objcontent'][0]['rowvalues'][i][0]
print(lat)
for i in lat:
result.append(i)
print (result)
Following is the output of print(lat):
92.213725
191.586143
228.981615
240.353291
and following is the output of print(result):
['9', '2', '.', '2', '1', '3', '7', '2', '5', '1', '9', '1', '.', '5', '8',
'6', '1', '4', '3', '2', '2', '8', '.', '9', '8', '1', '6', '1', '5', '2',
'4', '0', '.', '3', '5', '3', '2', '9', '1']
I expected to get the output in following format:
[92.213725, 191.586143, 228.981615, 240.353291]
Anyone knows how to fix this issue?
Thanks
So, your error is that instead of simply adding your latitute to the list, you are iterating over each character of the latitude, as a string, and adding that character to a list.
result=[]
for value in response_i['objcontent'][0]['rowvalues']:
lat = value[0]
print(lat)
result.append(float(lat))
print (result)
Besides that, using range(len(...))) is the way things have to be done in almost all modern languages, because they either don't implement a "for ...each" or do it in an incomplete or faulty way.
In Python, since the beginning it is a given that whenever one wants a for iteration he wants to get the items of a sequence, not its indices (for posterior retrieval of the indices). Some auxiliar built-ins come in to play to ensure you just interate the sequence: zip to mix one or more sequences, and enumerate to yield the indices as well if you need them.

How to split string array to 2-dimension char array in python

I have a string array, for example:
a = ['123', '456', '789']
I want to split it to form a 2-dimension char array:
b = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
I'm using
[[element for element in line] for line in array]
to achieve my goal but found it not easy to read, is there any built-in function or any readable way to do it?
Looks like a job for map:
>>> a = ['123', '456', '789']
>>> map(list, a)
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
Relevant documentation:
map
list
you could do something like:
first_list = ['123', '456', '789']
other_weirder_list = [list(line) for line in first_list]
Your solution isn't that bad, but you might do something like this or the map suggestion by arashajii.
map(list, array) should do it.
You can use map:
>>> a
['123', '456', '789']
>>> map(list, a)
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
Although I really don't see why you'd need to do this (unless you plan on editing one specific character in the string?). Strings behave similarly to lists.
First I tried e.split(''), but I get ValueError: empty separator.
Try this:
a = ['123', '456', '789']
b = [list(e) for e in a]
b
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]

Splitting a list in python

I'm writing a parser in Python. I've converted an input string into a list of tokens, such as:
['(', '2', '.', 'x', '.', '(', '3', '-', '1', ')', '+', '4', ')', '/', '3', '.', 'x', '^', '2']
I want to be able to split the list into multiple lists, like the str.split('+') function. But there doesn't seem to be a way to do my_list.split('+'). Any ideas?
Thanks!
You can write your own split function for lists quite easily by using yield:
def split_list(l, sep):
current = []
for x in l:
if x == sep:
yield current
current = []
else:
current.append(x)
yield current
An alternative way is to use list.index and catch the exception:
def split_list(l, sep):
i = 0
try:
while True:
j = l.index(sep, i)
yield l[i:j]
i = j + 1
except ValueError:
yield l[i:]
Either way you can call it like this:
l = ['(', '2', '.', 'x', '.', '(', '3', '-', '1', ')', '+', '4', ')',
'/', '3', '.', 'x', '^', '2']
for r in split_list(l, '+'):
print r
Result:
['(', '2', '.', 'x', '.', '(', '3', '-', '1', ')']
['4', ')', '/', '3', '.', 'x', '^', '2']
For parsing in Python you might also want to look at something like pyparsing.
quick hack, you can first use the .join() method to join create a string out of your list, split it at '+', re-split (this creates a matrix), then use the list() method to further split each element in the matrix to individual tokens
a = ['(', '2', '.', 'x', '.', '(', '3', '-', '1', ')', '+', '4', ')', '/', '3', '.', 'x', '^', '2']
b = ''.join(a).split('+')
c = []
for el in b:
c.append(list(el))
print(c)
result:
[['(', '2', '.', 'x', '.', '(', '3', '-', '1', ')'], ['4', ')', '/', '3', '.', 'x', '^', '2']]

Categories

Resources