Python Forum
Create a List for Boolean Mask.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create a List for Boolean Mask.
#1
Hi all,

I am trying to find a better way to create a Boolean Mask based on certain conditions. Here is the question and my way to answer it.

Question:
l = ["a","b","a","c"], "a" is a qualified data for the future use. Create a list with boolean values.

l = ["a","b","a","c"]
L = []
for i in l:
	if i == "a":
		L.append(True)
	else:
		L.append(False)
Result:
L = [True,False,True,False]

Thanks!
Reply
#2
You don't need the conditional. Just append i == 'a'.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
(Oct-08-2018, 09:59 PM)ichabod801 Wrote: You don't need the conditional. Just append i == 'a'.

Hi ichabod801, thanks for the solution.

Base on your reply, I tried a further simplification,

l = ["a","b","a","c"]
L = [x for x == 'a' in l]
python told me "invalid syntax"

Could you tell me the reason for this failure?
Reply
#4
You want
[x == 'a' for x in l]
Reply
#5
(Oct-09-2018, 12:03 AM)micseydel Wrote: You want
[x == 'a' for x in l]

Wow,it's like magic. Thanks!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Delete strings from a list to create a new only number list Dvdscot 8 1,466 May-01-2023, 09:06 PM
Last Post: deanhystad
  [split] why can't i create a list of numbers (ints) with random.randrange() astral_travel 7 1,428 Oct-23-2022, 11:13 PM
Last Post: Pedroski55
  Need to parse a list of boolean columns inside a list and return true values Python84 4 2,036 Jan-09-2022, 02:39 AM
Last Post: Python84
  how to easily create a list of already existing item CompleteNewb 15 3,375 Jan-06-2022, 12:48 AM
Last Post: CompleteNewb
  How do I mask Hex value wiht 0xFF? korenron 2 4,345 Nov-23-2021, 09:13 AM
Last Post: Gribouillis
  Create SQLite columns from a list or tuple? snakes 6 8,512 May-04-2021, 12:06 PM
Last Post: snakes
  Create variable and list dynamically quest_ 12 4,285 Jan-26-2021, 07:14 PM
Last Post: quest_
  How to create a linked list and call it? loves 12 4,356 Nov-22-2020, 03:50 PM
Last Post: loves
  Using boolean mask in Numpy for 3D IlikePi 0 1,471 Nov-14-2020, 10:08 PM
Last Post: IlikePi
  How to create and define in one line a 2D list of class objects in Python T2ioTD 1 1,986 Aug-14-2020, 12:37 PM
Last Post: Yoriz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020