List of even numbers at even number indexes using list comprehension [closed]

2024/10/5 14:57:27

I am trying to generate an even numbered list at even index locations using a list comprehension. The else values will be 0. I have done the function which does the same as below

def even_list(l):ll = []for x in l:if x%2 == 0:ll.append(x)ll.append(0)return ll[:-1]

Now I need to turn this into a list comprehension.

input = [11, 17, 12, 17, 40, 19, 12, 16]    
out = [12, 0, 40, 0, 12, 0, 16]

This is what I have tried (l is input and lo is out):

>>> l = [1, 2, 3, 4, 5, 6, 7]
>>> lo = []
>>> lo = [l[x] if l[x]%2 == 0 and len(lo)%2 == 0 else 0 for x in range(len(l))]
>>> print lo
[0, 2, 0, 4, 0, 6, 0]
Answer

I wasn't able to figure out exactly what you were looking for from your post, but here's what I think you want:

Given a list, get all the numbers at even indices. If any of these numbers are even, put them in a new list and return it:

In [10]: L = [3,1,54,5,2,3,4,5,6,5,2,5,3,2,5,2,2,5,2,5,2]In [11]: [num for i,num in enumerate(L) if not num%2 and not i%2]
Out[11]: [54, 2, 4, 6, 2, 2, 2, 2]

If you want to add 0s in between, then you can do a little itertools magic:

In [12]: list(itertools.chain.from_iterable(zip((num for i,num in enumerate(L) if not num%2 and not i%2), itertools.cycle([0]))))[:-1]
Out[12]: [54, 0, 2, 0, 4, 0, 6, 0, 2, 0, 2, 0, 2, 0, 2]

Ok, that was a lot of brackets and parentheses, so let's take a closer look at it:

  1. list(...)[:-1] converts ... into a list and gets all but the last element of that list. This is similar to what you were trying to do when you added 0s and removed the last one

  2. (num for i,num in enumerate(L) if not num%2 and not i%2) is the same as what it was before the edit, except that it uses parentheses (()) instead of brackets ([]). This turns it into a generator-comprehension, as opposed to a list comprehension - it only matters in that it performs a little bit of optimization - the values are not computed until they are needed (until zip asks for the next value)

  3. itertools.cycle([0]) gives an endless list of 0s

  4. zip(A, B) returns a list of tuples, in which the ith tuple has two elements - the ith element of A, and the ith element of B

  5. itertools.chain.from_iterable(zip(A, B)) returns the elements of A and B interleaved, as a generator. In essence, it's like doing this:

def someFunc(A, B):for i in range(len(A)):yield A[i]yield B[i]

Thus, all of these put together give you exactly what you want

https://en.xdnf.cn/q/120481.html

Related Q&A

How do I check if a list of lists exists in a list of lists?

I got a list of lists b and I want to check if they exist in list a which is also a list of lists. Im currently using the following method which is quite time-consuming. Is there a faster way? b = [[…

How do i print out a number triangle in python? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

Real time clock display in Tkinter

I want to create real time clock using Tkinter and time library. I have created a class but somehow I am not able to figure out my problem.My codefrom tkinter import *import timeroot = Tk()class Clock:…

cffi export python code to dll , how to read image object in @ffi.def_extern()

i am trying to convert my python code to dll using cffi so i can access this code in my c# apllication, and i am trying to send image my c# code to python function, below is my code to read the file an…

Python 2.7.5 and Python 3.6.5

I have installed Python 3.6.5 however when i type Python it shows Python 2.7.5. Id like to use Python 3.[aravind@aravind05 Python-3.6.5]$ python3 --version Python 3.6.5[aravind@aravind05 Python-3.6.5]$…

How use creating polynomial expression like function in Python?

Id like to write a program in Python where user define a deegre of polynomial and coefficients (a,b,c). When program create a polynomial expression with this data Id like to use it like function becaus…

how to merge two sublists sharing any number in common? [duplicate]

This question already has an answer here:Using sublists to create new lists where numbers dont repeat(1 answer)Closed 9 years ago.Given thatg=[[1,2,3,4],[4,5,6],[6,7],[10,11]]What code should I use to …

\n is treated as \ and n [duplicate]

This question already has an answer here:Compiler error "error: stray \ in program" in macro definition(1 answer)Closed 10 years ago.The following python codeenv.Command(versionFile, allSrcs …

How to locate an element and extract required text with Selenium and Python

I am using Selenium to enter data on a web page, but have run into an issue with one of the input fields. This is the HTML code causing my difficulty:<div class="form-group"> <label …

Determine type of disk on Windows with Python

I want to list all of my disk and can be able to know its type: "SATA" "NVME" "M.2" or "PCI" on Windows computer. I made some research with wmi and I get the int…