How to replace values using list comprehension in python3?

2024/11/15 21:08:25

I was wondering how would you can replace values of a list using list comprehension. e.g.

theList = [[1,2,3],[4,5,6],[7,8,9]]
newList = [[1,2,3],[4,5,6],[7,8,9]]
for i in range(len(theList)):for j in range(len(theList)):if theList[i][j] % 2 == 0:newList[i][j] = 'hey'

I want to know how I could convert this into the list comprehension format.

Answer

You can just do a nested list comprehension:

theList = [[1,2,3],[4,5,6],[7,8,9]]
[[x if x % 2 else 'hey' for x in sl] for sl in theList]

returns

[[1, 'hey', 3], ['hey', 5, 'hey'], [7, 'hey', 9]]
https://en.xdnf.cn/q/71847.html

Related Q&A

Installed PySide but cant import it: no module named PySide

Im new to Python. I have both Python 2.7 and Python 3 installed. I just tried installing PySide via Homebrew and got this message:PySide package successfully installed in /usr/local/lib/python2.7/sit…

How to run SQLAlchemy on AWS Lambda in Python

I preapre very simple file for connecting to external MySQL database server, like below:from sqlalchemy import *def run(event, context):sql = create_engine(mysql://root:[email protected]/scraper?chars…

saving csv file to s3 using boto3

I am trying to write and save a CSV file to a specific folder in s3 (exist). this is my code: from io import BytesIO import pandas as pd import boto3 s3 = boto3.resource(s3)d = {col1: [1, 2], col2: […

httplib2, how to set more than one cookie?

As you are probably aware, more often than not, an HTTP server will send more than just a session_id cookie; however, httplib2 handles cookies with a dictionary, like this:response, content = http.requ…

FTP upload file works manually, but fails using Python ftplib

I installed vsFTP in a Debian box. When manually upload file using ftp command, its ok. i.e, the following session works:john@myhost:~$ ftp xxx.xxx.xxx.xxx 5111 Connected to xxx.xxx.xxx.xxx. 220 Hello,…

Baktracking function which calculates change exceeds maximum recursion depth

Im trying to write a function that finds all possible combinations of coins that yield a specified amount, for example it calculates all possible way to give change for the amount 2 British pounds from…

How to interface a NumPy complex array with C function using ctypes?

I have a function in C that takes an array of complex floats and does calculations on them in-place.:/* foo.c */ void foo(cmplx_float* array, int length) {...}The complex float struct looks like this:t…

How to access predefined environment variables in conda environment.yml?

I wish to share an environment.yml file for others to reproduce the same setup as I have. The code we use depends on the environment variable $PWD. I wish to set a new env variable in the environment.y…

Python enclosing scope variables with lambda function

I wrote this simple code:def makelist():L = []for i in range(5):L.append(lambda x: i**x)return Lok, now I callmylist = makelist()because the enclosing scope variable is looked up when the nested functi…

Overloading + to support tuples

Id like to be able to write something like this in python:a = (1, 2) b = (3, 4) c = a + b # c would be (4, 6) d = 3 * b # d would be (9, 12)I realize that you can overload operators to work with custom…