Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a list like this:
my_lst = [[1,2,3,4]]
I was wondering how can I remove [] from the list to get the following list:
my_lst = [1,2,3,4]
The double [[]] is because you have a list containing a list. To get out the inner list, just index it:
my_lst = my_lst[0]
or unpack it:
[my_lst] = my_lst
Unpacking has the mild advantage that it will give you an error if the outer list doesn't not contain exactly one value (while my_lst[0] will silently discard any extra values).
There are many other options.
my_lst = my_lst[0]
You have a list with one element, which is itself a list. You want the variable to just be that first element, the list 1,2,3,4.
you have a list of lists.
my_lst = my_lst[0] #get the first list of the list
You can use itertools to achieve that without writing your explicit loop if the length of the outer list could be more than one.
In [47]: import itertools
In [49]: list(itertools.chain.from_iterable([[1, 2, 3], [1, 2]]))
Out[49]: [1, 2, 3, 1, 2]
You can reduce 1 dimension using sum.
my_lst=sum(my_lst,[])
# [1,2,3,4]
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
For a homework assignment I am given this task:
Read a list of numbers and generate a new list which squares the members of the original list.
generate a third list of ints that ranks the second list of ints.
What does it mean to "rank the list"? What is this asking me to do?
I am NOT asking for a solution to the programming assignment, please do not provide one.
To create a list of integers between 0 and N, a solution is to use the range(N) function.
Then you can use the append() method which adds an item to the end of the list while getting the square of each element.
Finally use the sort() method which sorts the list ascending by default. You can also make a function to decide the sorting criteria(s)
def printSortedList():
l = list()
for i in range(1,21):
l.append(i**2)
l.sort()
print(l)
printSortedList()
Ranking means to number the items in a list from lowest to highest, or vice-versa.
So, for example, “ranking” the list [639, 810, 150, 162, 461, 853, 648] produces the list [4, 6, 1, 2, 3, 7, 5], where 1 corresponds to the lowest value (150), 2 to the next-lowest value (162).
Or maybe you're supposed to rank them the other way, giving [4, 2, 7, 6, 5, 1, 3].
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How can I add a constant (ie 10) to a list without creating a new list?
For example,
list = [2, 4, 6, 8]
How can I overwrite the elements in this list without creating another list (append method)? I understand that there is a map lambda method. Any way to go about by using a for loop?
When x = 10, expected final output should be
list = [12, 14, 16, 18]
x = 10
for i in range(0, len(list)):
list[i] = list[i] + x
I kept the variable name as list, but I recommend you don't use built-in names as names for your variables.
You can for sure use the map function in Python as follows. I changed your list name to list1 to not confuse it with the datatype.
list1 = [2,4,6,8]
print(list(map(lambda x : x+10, list1)))
#Jax Teller 's solution is the standard.
Here is a generator, not changing the original, but instead yielding mapped values
Also, using the word list isn't good, because it is a Python construct. Use something else instead like my_list
my_list = [2,4,6,8]
val = 10
gen = (val + e for e in my_list)
This is actually the same as map.
Just notice you can't use list(gen) because it would create a new list, not just iterate.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am going through the exercises here: https://www.machinelearningplus.com/python/101-pandas-exercises-python/
Problem #16 has a solution (#1) using np.where() that I am having trouble understanding.
import pandas as pd
import numpy as np
print('pandas: {}'.format(pd.__version__))
print('NumPy: {}'.format(np.__version__))
print('-----')
ser1 = pd.Series([10, 9, 6, 5, 3, 1, 12, 8, 13])
ser2 = pd.Series([1, 3, 10, 13])
# Get the positions of items of 'ser2' in 'ser1' as a list.
# Solution 1
list1 = [np.where(i == ser1)[0].tolist()[0] for i in ser2]
print(list1)
print()
# Solution 2
list2 = [pd.Index(ser1).get_loc(i) for i in ser2]
print(list2)
I have looked up np.where() here:
# https://stackoverflow.com/questions/34667282/numpy-where-detailed-step-by-step-explanation-examples
# https://thispointer.com/numpy-where-tutorial-examples-python/
# https://www.geeksforgeeks.org/numpy-where-in-python/
To be precise, I am not understanding the function and placement of both
bracketed zero's ( [0] ).
np.where outputs a tuple (output of numpy.where(condition) is not an array, but a tuple of arrays: why?), so you'd have to index it (hence the first [0]), then, the output is a numpy array of elements. There is only one in this case, so the second [0] works. the tolist() is completely redundant though
It'd be better to extend list1 with the found indexes, because this code fails when an element occurs more than once:
list1 = []
[list1.extend(np.where(i == ser1)[0]) for i in ser2]
print(list1)
print()
Not the best code imo.
tip, just check the output of stuff yourself, and you would have figured this out. just run np.where(i==ser1) and you'd have seen it returns a tuple, and you need to index it. etc.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Say I've a list with a fixed size and elements.
I wish to create set of all possible combinations of the elements inside the array. How do I achieve this?
In python I've tried to use itertools like this:
import itertools
a = [4, 7]
for L in range(0, len(a)+1):
for subset in itertools.combinations(a, L):
print(subset)
Howsoever, this gives me an output(),(4),(7),(4,7) as in tuples. I want 4,7,47,74 as my desired output in a list or array(C++) and not to print them after each loop iteration.
I don't know if that's permutation or combination. So kindly bear with me and help.
From your sample output (which by the way is not in agreement with your input), it is clear that you don't need combinations but permutations from itertools. You can use join to merge your two numbers for printing purpose.
Most importantly, you should start your loop over L from 1 because you need at least length of 1 to generate the permutations other wise you will get empty lists (tuples) as you mentioned in your question.
import itertools
a = [4, 7]
lst = []
for L in range(1, len(a)+1):
for subset in itertools.permutations(a, L):
lst.append(''.join(str(x) for x in subset))
for l in lst:
print (l)
Output
4
7
47
74
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hi guys i have a dictionary that looks like this:
[[['Test', 0,1],['Test2', 0,4],['Test3', 0,5],['Test4', 0,2],['Test5', 0,6],...]]
How can I get the top two (for example)?
Expected result:
[['Test3', 0,5],['Test5',0,6]]
Sort by the third value:
>>> sorted(l[0], key=lambda x: x[2])[-2:]
[['Test3', 0, 5], ['Test5', 0, 6]]
test = [[['Test', 0,1],['Test2', 0,4],['Test3', 0,5],['Test4', 0,2],['Test5', 0,6]]]
result = sorted(test[0], key=lambda x: x[2])[-2:]
print(result)
Output:
[['Test3', 0, 5], ['Test5', 0, 6]]
Something like this?
(I am assuming that you actually mean ['Test', 0, 1] to be a list with 3 elements which is to be sorted by the third element rather than a two element list with the second element being a float, in which case it should be ['Test', 0.1] and you can look at #jonrsharpe's answer. I also assumed that the output order (lowest to highest) is relevant.)
That is not a dictionary, it is a list ([]) containing another list which contains lists. Each sub-sub-list contains three elements:
['Test2', 0, 4]
#^0 ^1 ^2
Note that Python doesn't allow the user of commas as decimal points; I think you want 0.4.
Assuming that, sorting the sub-list and extracting the two highest sub-sub-lists is easy:
from operator import itemgetter
output = sorted(lst[0], key=itemgetter(1), reverse=True)[:2]
If I am wrong about the comma, make the argument to itemgetter 2.