[英]How do I create a list from one list of integers and one list of booleans? (Python)
[英]How can I create a list of R=10000 booleans called inside in Python?
import random, math
random.seed(1)
def in_circle(x, origin = [0]*2):
"""
This function determines if a two-dimensional point
falls within the unit circle.
"""
if len(x) != 2:
return "x is not two-dimensional!"
elif distance(x, origin) < 1:
return True
else:
return False
print(in_circle((1,1)))
接下來,我想使用函數“ in_circle”確定x中的每個點是否落在以(0,0)為中心的單位圓內。 我該怎么做? 我的編程水平-初學者
我不知道您的distance
函數是什么樣子,但是假設傳遞給該函數的x
變量具有10000點,這是計算布爾數組的一種方式。 當調用該函數in_circle
,你可以通過你的陣列/列表中的所有10000點,並更換[(1,1), (1,2), (2,2)])
在in_circle([(1,1), (1,2), (2,2)])
包含點的數組/列表。 讓我知道它是否無效。
在此解決方案中,您將通過將所有10000個點一起傳遞in_circle
一次調用in_circle
函數,然后for
循環將計算函數內部的距離。 在我看來,這比將for
循環放到外部並為每個點一一調用該函數10000次更好。
import random, math
random.seed(1)
def in_circle(x, origin = [0]*2):
bool_array = []
for point in x: # assuming x contains 10000 points
if len(x) != 2:
print ("x is not two-dimensional!")
continue
elif distance(x, origin) < 1:
bool_array.append(True)
else:
bool_array.append(False)
return bool_array
bool_array = in_circle([(1,1), (1,2), (2,2)])
嗨,只需將1000點或任意數量的坐標放在下面的列表li中,然后使用循環在其上運行函數,即可將布爾值放入列表X中。例如:
x=[] #declare an empty list where boolean value needs to be stored
li=[(1,1),(0,0),(-1,1)]
for i in range(0,len(li)):
x1=in_circle(li[i])
x.append(x1)
據我了解,您有像這樣的元組列表
l = [(x1, y1),
(x2, y2),
...
(x10000, y10000)]
在這種情況下,您需要對其進行迭代
但首先,創建一個包含布爾值的列表
bools = []
for xy in l: # xy is tuple
bools.append(in_circle(xy))
那是初學者的水平,但是甚至有更好的方法:
bools = [in_circle(xy) for xy in l]
如果是編程初學者的杠桿,您會發現對這些概念也很有用,它們將對您的程序員將來派上用場:
map
, lambda
和generators
。
如:
in_circle = lambda (x, y): True if Math.sqrt( Math.pow(x,2) + Math.pow(y,2) ) < 1 else False
# assuming circle has center 0, 0 and radius 1
2.然后將函數映射到點列表:
map( in_circle, your_list)
請注意,在lambda中,語法(x,y)是因為您將元組作為一個參數傳遞,並且列表的格式如下:
your_list = [(0,1),(0, 0.5), (0.3, 0.4) ...]
3.除了列表以外,您還可以使用生成器,如果您不需要再次使用列表,則該結構在迭代中非常方便。
語法類似(請注意剎車!(VS [)
your_point = [ (random.random(), random.random()) for i in range(n) ]
# list comprehension
your_point = ( (random.random(), random.random()) for i in range(n) )
# generator
4.因此,您可以生成N個布爾值的列表,例如:
n = 10000
your_point = ( (random.random(), random.random()) for i in range(n) )
bool_list = map( in_circle, your_list)
為了您對lamdba和常規函數之間的區別有所好奇,另請參見: lambda和常規函數之間python有什么區別?
對於您對生成器VS列表理解的興趣: 生成器表達式與列表理解
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.