Can list become an element of set in python - python-2.7

I really wonder why the second one gives an error:
It would be really great if some one could pls highlight can we use lists as an element in set or it's not allowed to have any mutable object inside a set.
1)
>>> x = set(["Perl", "Python", "Java"])
>>> x
set(['Python', 'Java', 'Perl'])
>>>
2)
>>> cities = set((["Python","Perl"], ["Paris", "Berlin", "London"]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>>

As you noted, you can't have a list as a member of a set (because it's not hashable).
I think you've been confused by the repr of the set in your first example. The output set(['Python', 'Java', 'Perl']) doesn't indicate that the set contains a 3-element list. Rather, it contains the three strings, with the list just being part of the notation the repr uses (since the set constructor expects an iterable of items). Note that the order of the items changes from your input to the the arbitrary order of the output!
In Python 3, the set type's repr uses set-literal syntax instead:
>>> x = set(["Perl", "Python", "Java"])
>>> x
{'Java', 'Perl', 'Python'}

Related

python 3 print list of integer without spaces

In python 3.10 I created a function that generates a list with 6 integers.
I want to print the list of integers within a string, including brackets, but without spaces.
def create_grid(number):
n = number
return [n, n+2, n+4, n+1, n+3, n+5]
l = create_grid(0)
print(l)
[0, 2, 4, 1, 3, 5]
type(l)
<class 'list'>
Desired output: "text prepend [0, 2, 4, 1, 3, 5] text append"
I've tried it with join as suggested in 17190709
print('[{0}]'.format(','.join(map(str, l))))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
Other methods complain the list elements are integers, not the expected string. Or print it with spaces anyway.
The one way I could get working was calling each element in f-string
print(f'text prepend [{l[0]},{l[1]},{l[2]},{l[3]},{l[4]},{l[5]}] text append')
text prepend [0,2,4,1,3,5] text append
I've been scratching my head for a better option, curious if any of you can come up with one.
Thanks in advance!

Convert a single list item of key value pair to an dictionary in python

I have function that returns just one list of key-value pair. How can I convert this to an actual key value or an object type so I can get each attribute from the list. For example I would like to be able to just get the time or price or any other property and not the whole list as one item.
{'time': 1512858529643, 'price': '0.00524096', 'origQty': '530.00000000'
I know it doesn't look like a list but it actually is! The function that I am calling returns this as a list. I am simply storing it to a variable and nothign else.
open_order=client.get_open_orders(symbol="BNBETH",recvWindow=1234567)
If you still have doubts. When I try to print a dictionary item like this print(open_order['time'])
I get the following error.
Traceback (most recent call last):
File "C:\Python27\python-binance-master\main.py", line 63, in <module>
print(open_order['time'])
TypeError: list indices must be integers, not str
Also If I show type it shows as list.
print(type(open_order))
So, I was able to come up with a solution, sort of... by converting the list to string and splitting at the "," character. Now I have list of items that I can actually print by selecting one print(split_order_items[5]) There has to be a better solution.
open_order=client.get_open_orders(symbol="BNBETH",recvWindow=1234567)
y=''.join(str(e)for e in open_order)
split_order_items =([x.strip() for x in y.split(',')])
print(split_order_items[5])
I was able to create a multiple list items using the above code. I just can't seem to convert it to dictionary object!
Thanks!
What you have posted is a dict, not a list. You can do something like this:
data = {'time': 1512858529643, 'price': '0.00524096', 'orderId': 7848174, 'origQty': '530.00000000'}
print(data['time']) # this gets just the time and prints it
print(data['price']) # this gets just the price and prints it
I strongly suggest reading up on the Python dict: https://docs.python.org/3/tutorial/datastructures.html#dictionaries

Python strip() and readlines()

I have a code that I am trying to run which will compare a value from a csv file to a threshold that I have set within the py file.
My csv file has an output similar to below, but with 1030 lines
-46.62
-47.42
-47.36
-47.27
-47.36
-47.24
-47.24
-47.03
-47.12
Note: there are no lines between the values but there is a single space before them.
My first attempt was with this code:
file_in5 = open('710_edited_capture.csv', 'r')
line5=file_in5.readlines()
a=line5[102]
b=line5[307]
c=line5[512]
d=line5[717]
e=line5[922]
print[a]
print[b]
print[c]
print[d]
print[e]
which gave the output of:
[' -44.94\n']
[' -45.06\n']
[' -45.09\n']
[' -45.63\n']
[' -45.92\n']
My first thought was to use .strip() to remove the space and the \n but this is not supported in lists and returns the error:
Traceback (most recent call last):
File "/root/test.py", line 101, in <module>
line5=line5.strip()
AttributeError: 'list' object has no attribute 'strip'
My next code below:
for line5 in file_in5:
line5=line5.strip()
line5=file_in5.readlines()
a=line5[102]
b=line5[307]
c=line5[512]
d=line5[717]
e=line5[922]
print[a]
print[b]
print[c]
print[d]
print[e]
Returns another error:
Traceback (most recent call last):
File "/root/test.py", line 91, in <module>
line5=file_in5.readlines()
ValueError: Mixing iteration and read methods would lose data
What is the most efficient way to read in just 5 specific lines without any spaces or \n, and then be able to use them in subsequent calculations such as:
if a>threshold and a>b and a>c and a>d and a>e:
print ('a is highest and within limit')
CF=a
You can use strip(), but you need to use read() instead of readlines(). Another way, if you have more than one value in a row with comma separation, you can use the code as below:
with open('710_edited_capture.csv', 'r') as file:
file_content=file.readlines()
for line in file_content:
vals = line.strip().split(',')
print(vals)
You can also append "vals" to an empty list. As a result, you will get a list that contains a list of values for each line.
it's a little bit unclear what you want to do but if you just want to read a file compare each value to a threshold value and keep upper value here a example :
threshold=46.2
outlist=[]
with open('data.csv', 'r') as data:
for i in data:
if float(i)>threshold:
outlist.append(i)
then you can adapt it to your needs...
Thanks for all the comments and suggestions however they are not quite what I needed.
I have however applied a workaround, although admittedly clunky.
I have created 5 additional files from the original with only the one value in each. From this I can now strip the space and /n and save them locally as a variable. I no longer needed the readlines
These variables can be compared to each other and the threshold to determine the optimum choice.

Python 2.7.10 ValueError: Incomplete Format if statement

def func():
import csv
file=open("cmiday.csv")
x,y=[],[]
reader=csv.DictReader(file)
for row in reader:
if(type(row["max_rel_hum"])%1==0):
continue
if(type(row["precip"])%1==0):
continue
if(row["max_rel_hum"]>100):
continue
if(row["max_rel_hum"]<0):
continue
if (row["precip"]>10):
continue
if(row["precip"]<0):
continue
x.append(row["max_rel_hum"])
y.append(row["precip"])
print x
print y
I'm trying to collect data from a csv file into lists x and y. I don't want any values for row["max_rel_hum"] to be integers or be more than 100 or less than 0. Similarly, I don't want any values for row["precip"] to be more than 10 or less than 0. I'm getting this error when I try to run the function:
>>> func()
Traceback (most recent call las
File "<stdin>", line 1, in <m
File "hw.py", line 7, in func
if(row["max_rel_hum"]%1==0)
ValueError: incomplete format
Please help out. Thanks
Values from a CSV are strings, not integers. You're expecting % to do modulo, but on a string it does string formatting.
You need something like this:
if ( int(row["max_rel_hum"]) % 1 == 0):
And you need to do int() for in all the lines, even the < and > ones - they are valid operations on strings, but will do an alphabetical order comparison, not a numeric comparison, and won't give the results you expect.
You don't need type() in the if line at all.

Why do I get a TypeError here?

if emp in like_list[j]:
TypeError: coercing to Unicode: need string or buffer, list found
Both emp and like_list are lists containing strings.
Because both emp and like_list are lists, you are essentially looking for a list within a list.
If you're trying to match any element within list emp, you can iterate over the list like this:
for element in emp:
if element in like_list:
--do something--
else:
--do something else--
Alternatively, if like_list were a list of lists, your if statement would work.
If both emp and like_list are lists of strings, the expression emp in like_list[j] is checking if a list is a member of a single string. When I tested it out with the code below I got a slightly different TypeError:
>>> emp = ["foo", "bar"]
>>> like_list = ["baz", "quux"]
>>> if emp in like_list[0]:
... print "found"
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
This says that you can't test non-strings for membership in a string. I think fixing this will be pretty easy, but it's not entirely clear what you were trying to do.
If you want to check if the string like_list[j] has one of the strings in emp as a substring, use:
if any(s in like_list[j] for s in emp):
If instead you want to see if like_list[j] is equal to one of the strings in emp, you need to turn around the in expression:
if like_list[j] in emp: