Bottom Page

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!
Quote
#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

Quote
#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?
Quote
#4
You want
[x == 'a' for x in l]
Feel like you're not getting the answers you want? Checkout the help/rules for things like what to include/not include in a post, how to use code tags, how to ask smart questions, and more.

Pro-tip - there's an inverse correlation between the number of lines of code posted and my enthusiasm for helping with a question :)
Quote
#5
(Oct-09-2018, 12:03 AM)micseydel Wrote: You want
[x == 'a' for x in l]

Wow,it's like magic. Thanks!
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Create a dictionary from a list klllmmm 3 152 Oct-06-2019, 05:50 PM
Last Post: Gribouillis
  How to create a list with all values being zero 357mag 4 248 Jul-14-2019, 03:43 PM
Last Post: ThomasL
  Create new list from another list based on condition khalidreemy 1 286 Jun-11-2019, 10:21 AM
Last Post: buran
  Subnet Mask Ranges ab52 0 280 Mar-11-2019, 10:39 AM
Last Post: ab52
  How to create meshgrid with non-integer stepsize of list elements? dazzabaijan 1 338 Mar-11-2019, 02:00 AM
Last Post: ichabod801
  create list from repeated pattern in python Code4fun 2 720 Sep-25-2018, 07:09 PM
Last Post: woooee
  Create Alert if string from list appears on other list javalava 1 468 Sep-17-2018, 02:44 PM
Last Post: DeaD_EyE
  python script to get wildcard mask output in the following format techrichit 0 807 Aug-10-2018, 11:01 PM
Last Post: techrichit
  create folders named from list array HaKDMoDz 1 588 Jul-19-2018, 06:09 AM
Last Post: buran
  Help writing code to create a ranked list swilson421 2 606 Jul-16-2018, 04:51 PM
Last Post: swilson421

Forum Jump:


Users browsing this thread: 1 Guest(s)