Ideas for the following function? - python

I would like to develop a function which would always based on the first element in the list extract further elements of the nested list.
Example:
Input:
lst= [[1,2,3],[3,4,5,6,8,9], [0,3,4], [1,4,5,6], [4,9,8,6,5,2]]
The first element in the sublist always determines the number of following elements to append to a new list.
Output:
Out=[2,4,5,6,4,9,8,6,5]
Elements are always an integer values.

Maybe this is what you expect:
Or you can convert this to List Comprehension later.
out = []
for sub in lst: # loop each sublist
start = sub[0] # use the first num. to determine
out.extend(sub[1: 1+start]) # get each sublist by slicing
print(out)
[2, 4, 5, 6, 4, 9, 8, 6, 5]

Related

Extract indices of certain values from a list in python

Suppose, I have a list [0.5,1,1.5,2,2.5,3,3.5,4,4.5], now I would like to extract the indices of a list [1.5,2.5,3.5,4.5], which is a subset of that list.
You can use the inbuilt function <list>.index to find the index of each element(of second list) in the first list.
Having that learnt, you can use list comprehension to achieve what you want:
>>> list1 = [0.5,1,1.5,2,2.5,3,3.5,4,4.5]
>>> list2 = [1.5,2.5,3.5,4.5]
>>> [list1.index(elem) for elem in list2]
[2, 4, 6, 8]
One other option is to use enumerate function. See the following answer:
a = [0.5,1,1.5,2,2.5,3,3.5,4,4.5]
b = [1.5,2.5,3.5,4.5]
indexes = []
for id, i in enumerate(a):
if i in b:
indexes.append(id)
print(indexes)
The output is going to be [2, 4, 6, 8].

How remove() function was executed in python?

Actually I was working with this code:
m=[0,1,2,3,4,5,6,7]
for i in m:
m.remove(i)
print(m)
This looks pretty simple.
for i in m:
print(i)
will print every elements in the list m. So the for part in our code will extract every elements of the list and remove it one by one. So the output that I except is [].
But I got [1,3,5,7].
How it can be the output and where I was wrong?
when you use (for i in m), i starts from index zero so i is the element of index 0 which its value is 0 then in for loop you'll delete zero value.
now your list is [1,2,3,4,5,6,7] and i is the element of index 1 which its value is 2.
after deleting 2 your list would be like [2,3,4,5,6,7], now i is the element of index 2 which its value is 4 and ....
here is how this for loop works and why the output is like that.
to remove all element in a list you can use:
for i in range(len(m)):
m.remove(m[0])
or
m.clear()
If you know how to use a debugger, that would be the ideal way to diagnose this, otherwise, try running this code to see what's going on:
x = [0, 1, 2, 3, 4, 5, 6, 7]
for i in x.copy():
x.remove(i)
print(x)
print(x)
m = [0, 1, 2, 3, 4, 5, 6, 7]
for i in m:
m.remove(i)
print(m)
print(m)
During a given execution, the for loop accesses an element and then deletes it. For example, it first deletes the element at index 0, with value 0, leaving you with [1, 2, 3, 4, 5, 6, 7]. Then it moves on to the element at index 1, value 2, and deletes that, leaving you with [1, 3, 4, 5, 6, 7].
In general, avoid messing around with a list in Python. If you have to delete all elements, use m.clear(). If you have to delete some elements or do some other stuff, prefer to use list comprehension to create a new object.
What happens here is, you're removing items in the list on the go.
Eg,
On the first remove() call, it removes 0 from the list (current
index is 0).
On the second remove() call, the current index is 1,
but the list contains [1,2,3,...]. Now the the index 1 contains "2"
instead of "1". Because 0 has been removed and the size of list is
just changed.
So to clear list in python, you can use,
m.clear()
i don`t know why it is not remove each item, but i worked on it and it works like this:
m=[0,1,2,3,4,5,6,7]
while m != []:
[m.remove(i) for i in m]
print(m)

how to remove the last digit in a list if the list contain number last number some were in the list

i need to remove a digit in the given list,But while executing this first digit is removed
python pycharm
l = [4, 2, 6, 4, 7]
l.remove(l[3])
print(l)
expected output:[4, 2, 6, 7]
But I get: [2, 6, 4, 7]
To remove an item from a list given an index, use list().pop() like so:
l.pop(3) # Remove the third element.
It has 3 methods to remove an element from python List.
You can read more about list in here
list.pop(3) # remove 4th element
del list(3) # remove 4th element
list.remove(value1) # remove element have value1 in list
Avoid using a direct pop() function if your list is dynamically generating because you don't know the index of elements.
The enumerate() function adds a counter to an iterable.
So for each element in a cursor, a tuple is produced with (counter, element).
list1 = [4, 2, 6, 4, 7]
new_list = []
for index,elm in enumerate(list1):
if elm not in (list1[:index]):
new_list.append(elm)
print(new_list)
O/P:
[4, 2, 6, 7]

List Duplicate Removal Issue?

I wrote a code that eliminates duplicates from a list in Python. Here it is:
List = [4, 2, 3, 1, 7, 4, 5, 6, 5]
NewList = []
for i in List:
if List[i] not in NewList:
NewList.append(i)
print ("Original List:", List)
print ("Reworked List:", NewList)
However the output is:
Original List: [4, 2, 3, 1, 7, 4, 5, 6, 5]
Reworked List: [4, 2, 3, 7, 6]
Why is the 1 missing from the output?
Using set() kills the order. You can try this :
>>> from collections import OrderedDict
>>> NewList = list(OrderedDict.fromkeys(List))
You missunderstood how for loops in python work. If you write for i in List: i will have the values from the list one after another, so in your case 4, 2, 3 ...
I assume you thought it'd be counting up.
You have several different ways of removing duplicates from lists in python that you don't need to write yourself, like converting it to a set and back to a list.
list(set(List))
Also you should read Pep8 and name your variables differently, but that just btw.
Also if you really want a loop with indices, you can use enumerate in python.
for idx, value in enumerate(myList):
print(idx)
print(myList[idx])
Your code is not doing what you think it does. Your problem are these two constructs:
for i in List: # 1
if List[i] # 2
Here you are using i to represent the elements inside the list: 4, 2, 3, ...
Here you are using i to represent the indices of the List: 0, 1, 2, ...
Obviously, 1. and 2. are not compatible. In short, your check is performed for a different element than the one you put in your list.
You can fix this by treating i consistently at both steps:
for i in List:
if i not in NewList:
NewList.append(i)
Your method for iterating over lists is not correct. Your code currently iterates over elements, but then does not use that element in your logic. Your code doesn't error because the values of your list happen also to be valid list indices.
You have a few options:
#1 Iterate over elements directly
Use elements of a list as you iterate over them directly:
NewList = []
for el in L:
if el not in NewList:
NewList.append(i)
#2 Iterate over list index
This is often considered anti-pattern, but is not invalid. You can iterate over the range of the size of the list and then use list indexing:
NewList = []
for idx in range(len(L)):
if L[idx] not in NewList:
NewList.append(i)
In both cases, notice how we avoid naming variables after built-ins. Don't use list or List, you can use L instead.
#3 unique_everseen
It's more efficient to implement hashing for O(1) lookup complexity. There is a unique_everseen recipe in the itertools docs, replicated in 3rd party toolz.unique. This works by using a seen set and tracking items as you iterate.
from toolz import unique
NewList = list(unique(L))

Mapping a dictionary key and its corresponding values from a list?

I've managed to read in a .txt file and read in each line as a different element of a list; pretty easy. Next I stripped all the non-numerical characters from each element (leaving just 0-9 and '.'), also pretty easily done.
However, then I'm left with a list with 90 total elements. Starting from element 0, I want every 5th element to be the key to my dictionary (0, 5, 10, 15, etc). Then I want the 4 value in between to correspond to the values of the previous key (as a list length 4).
For example:
my_list[0] is the key with corresponding values my_list[1:5]
my_list[5] is the key with corresponding values my_list[6:10]
etc, etc
I've managed to take every 5th element out and make it it's own list; just holding the keys. And I've even managed to create another list which holds all the in between values as seperate lists of length 4.
I've tried:
my_dict = dict()
for i in my_keys:
my_dict[i] = [x for x in every_four]
AND
my_dict = dict()
for i in my_keys:
for x in every_four:
my_dict[i] = x
The first one gives me the correct keys but each value is just a the whole every_four list, not just every element. The second one gives me the correct keys but each value is just the first element of the every_four list, it's not iterating through.
Can someone help me get it working this way? And is there any easier way I can do this from the original array? Just set every 5th element to a key and the four elements in between as the corresponding values for that key?
If you want every fifth element as key of your dictionary and list of next consecutive four elements as values, then you can try dictionary comprehension.
my_dict = {my_list[i] : my_list[i+1 : i+5] for i in range(0, len(my_list), 5)}
For sample input -
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
output will be -
{0: [1, 2, 3, 4], 5: [6, 7, 8, 9]}
But this code will generate an empty list as value if for a key no next element is present.
Input -
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Output -
{0: [1, 2, 3, 4], 10: [], 5: [6, 7, 8, 9]}
As for your code, assuming you get every_four and my_keys correct, there are some problems. In your second attempt, you are looping over every element in the my_keys list and adding that as key of the dictionary. And in the inner loop you are adding x as the value of the dictionary. So, for every iteration in your inner loop, the value for key i is getting overwritten.
What you could have done is -
my_dict = dict()
for i in my_keys:
for x in every_four:
my_dict.setdefault(i, []).append(x)
For first attempt, I really need to see how you get my_keys and every_four to point out the error.

Categories

Resources