I have this:
lst = [2,2,3,3]
c1 = Counter(lst)
x = c1.values()
I want to know why I get this:
x = dict_values([2, 2])
and what can i do to get this:
x = [2,2]
I want to do this so I can manipulate and compare the data inside, the only way I have found is by doing
x = []
for i in c1.values():
x.append(i)
but I was looking for a more direct way to do this, like
x = c1.values()
I tried looking on the net but I can't find anything
You can turn any iterable (including a dict_values) into a list by passing it to the builtin list constructor:
x = list(c1.values())
Never use builtin names like list or dict as variable names; if you do, like you did here:
list = [2,2,3,3]
you won't be able to use the builtin list any more because you've overwritten its name. You'll need to edit your code to change the name of that variable before trying to use list(c1.values()).
The values returned by calling .values() on a dictionary are wrapped within a dict_values object. You can convert it into a normal list using:
x = list(c1.values())
Or, using your loop logic, but applying it directly to Counter and within a list-comprehension:
x = [v for v in Counter(list).values()]
Also as a general hint I would avoid using the names of python builtins such as list as variable names as that can cause problems and unexpected behaviours.
Related
(I wrote list instead of the actual list names for better understanding)
I'm reading from a file with one number at each line. Then I made it into a list[] and I did list.append(line.replace("\n", "").strip())
When executing the function I wrote - list = inteles(list)
I tried restarting vs code, but it didn't work.
Why not list.append(int(line.replace("\n", "").strip()))
Since when you say for x in y, the x you get isn't able to change the value of the real x in the list. (except with modifying class attributes I believe)
To fix this, just do a list comprehension:
def inteles(lista):
return [int(ele) for ele in lista]
You are not changing the value of the original list, you are not creating a new list either, you are just changing the value of a local variable (to that function). If you want to get a list with all strings converted to a integer, you should create a new list in the function and append the changed local variable to that local list and then return that local list.
Below is a example of that:
foist = [1, 3, "4", "72"]
def inteles(lista):
newlist = []
for sor in lista:
sor = int(sor)
newlist.append(sor)
return(newlist)
Please let me know how this for loop is working.
points = {0,1,2,3,4,8,1}
x = float(sum([len(points) for i in points]))
print(x)
This code snippet is giving me output as:-
36.0
List comprehensions are not that hard if you take a look at a very simple example:
[T(x) for x in X]
The first term is declaring what should be done with all the individual items in the collection we are iterating over. This might be type conversion or just extracting a specific value from a dict.
The symbol after the for just defines the name for our iteration variable and the last term is the collection(list, set, dict etc.) which we iterate through.
A more verbose implementation of the same thing could be:
result = []
for i in range(len(X)):
result.append(T(X[i]))
After this the content of result is the same as the list returned by the list comprehension.
I was writing a function to save unique values returned by a list "list_accepted_car" to a set "unique_accepted_ant". list_car_id is list with the value ['12','18','3','7']. When i run the code i am getting error , "unhashable list ". Can anyone suggest me what is the error?
list_accepted_car = [] #set to store the value list_accepted_car
unique_accepted_car = set() #set to store the value unique_accepted_car
num_accepted = 2 #predifined value for the number of cars allowed to enter
def DoIOpenTheDoor(list_car_id): #list_ant_id is a list of cars allowed to enter
if len(list_accepted_car) < num_accepted:
if len(list_car_id) > 0:
list_accepted_car.append(list_car_id[0:min(len(list_car_id),num_accepted-len(list_accepted_car))])
unique_accepted_list = set(list_accepted_car)
print unique_accepted_list
return list_accepted_car
Under the assumption that list_car_id looks like: [1,2,3,4,5].
You add in list_accepted_car a sublist of list_car_id, so list_accepted_car will look like [[1,2]] i.e. a list of a list.
Then you should change
unique_accepted_list = set(list_accepted_car)
to
unique_accepted_list = set([x for y in list_accepted_car for x in y])
which will extract each element of the sublist and provide a flatten list. (There exists other options to flatten a list of list)
You are saving a list of lists, which can't be converted to a set. You have to flatten it first. There are many examples of how to do it (I'll supply one using itertools.chain which I prefer to python's nested comprehension).
Also, as a side note, I'd make this line more readable by separating to several lines:
list_accepted_car.append(list_car_id[0:min(len(list_car_id),num_accepted-len(list_accepted_car))])
You can do:
from itertools import chain
# code ...
unique_accepted_list = set(chain.from_iterable(list_accepted_car))
The best option would be to not use a list at all here, and use a set from the start.
Lists are not hashable objects, and only hashable objects can be members of sets. So, you can't have a set of lists. This instruction:
list_accepted_car.append(list_car_id[0:min(len(list_car_id),num_accepted-len(list_accepted_car))])
appends a slice of list_car_id to list_accepted_car, and a slice of a list is a list. So in effect list_accepted_car becomes a list of lists, and that's why converting it to a set:
unique_accepted_list = set(list_accepted_car)
fails. Maybe what you wanted is extend rather than append? I can't say, because I don't know what you wanted to achieve.
I have defined a function called modify which modifies given string. I have a dict called elements which have some strings stored in them. However, I am unable to modify those strings stored in the dict.
x = "abc"
x = modify(x)
This works but when I do;
for element in elements:
element = modify(element)
This does not work. Any idea why? I'm fairly new to python.
You cannot modify the elements of a dict whilst iterating through them.
You'd need to use something like this:
for key in elements:
elements[key] = modify(elements[key])
If you need to apply a function to each member of a dictionary, consider using a dict comprehension:
elements = {k: modify(v) for k, v in elements.items()}
If you are using python 2.7 use elements.iteritems() instead of elements.items().
I'm trying to add items to an array in python.
I run
array = {}
Then, I try to add something to this array by doing:
array.append(valueToBeInserted)
There doesn't seem to be a .append method for this. How do I add items to an array?
{} represents an empty dictionary, not an array/list. For lists or arrays, you need [].
To initialize an empty list do this:
my_list = []
or
my_list = list()
To add elements to the list, use append
my_list.append(12)
To extend the list to include the elements from another list use extend
my_list.extend([1,2,3,4])
my_list
--> [12,1,2,3,4]
To remove an element from a list use remove
my_list.remove(2)
Dictionaries represent a collection of key/value pairs also known as an associative array or a map.
To initialize an empty dictionary use {} or dict()
Dictionaries have keys and values
my_dict = {'key':'value', 'another_key' : 0}
To extend a dictionary with the contents of another dictionary you may use the update method
my_dict.update({'third_key' : 1})
To remove a value from a dictionary
del my_dict['key']
If you do it this way:
array = {}
you are making a dictionary, not an array.
If you need an array (which is called a list in python ) you declare it like this:
array = []
Then you can add items like this:
array.append('a')
Arrays (called list in python) use the [] notation. {} is for dict (also called hash tables, associated arrays, etc in other languages) so you won't have 'append' for a dict.
If you actually want an array (list), use:
array = []
array.append(valueToBeInserted)
Just for sake of completion, you can also do this:
array = []
array += [valueToBeInserted]
If it's a list of strings, this will also work:
array += 'string'
In some languages like JAVA you define an array using curly braces as following but in python it has a different meaning:
Java:
int[] myIntArray = {1,2,3};
String[] myStringArray = {"a","b","c"};
However, in Python, curly braces are used to define dictionaries, which needs a key:value assignment as {'a':1, 'b':2}
To actually define an array (which is actually called list in python) you can do:
Python:
mylist = [1,2,3]
or other examples like:
mylist = list()
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist)
>>> [1,2,3]
You can also do:
array = numpy.append(array, value)
Note that the numpy.append() method returns a new object, so if you want to modify your initial array, you have to write: array = ...
Isn't it a good idea to learn how to create an array in the most performant way?
It's really simple to create and insert an values into an array:
my_array = ["B","C","D","E","F"]
But, now we have two ways to insert one more value into this array:
Slow mode:
my_array.insert(0,"A") - moves all values to the right when entering an "A" in the zero position:
"A" --> "B","C","D","E","F"
Fast mode:
my_array.append("A")
Adds the value "A" to the last position of the array, without touching the other positions:
"B","C","D","E","F", "A"
If you need to display the sorted data, do so later when necessary. Use the way that is most useful to you, but it is interesting to understand the performance of each method.
I believe you are all wrong. you need to do:
array = array[] in order to define it, and then:
array.append ["hello"] to add to it.