S0=['S1','S2','S3']
P=[]
def du(S0,P):
for i in range(len(S0)):
def d(S0[i]):
d=0
for n in range(len(P)):
if S0[i] in P[n]:
d=d+1
return d
if d(S0[i])==0:
......
这里我想以 S0[i]
作为 d()
的参数,请问怎样可以实现以带下标的 list 作为函数参数? 或者有什么可以替代的方法?。
这个 d()
函数是要对 S0
中的每个元素进行分析的,我是想做一个简单的多边形拓扑关系的程序,要计算每条边(也就是 S0[i]
)的度,当度大于 2 时把这条边从 S0
里删掉。
这里用 range
而不是直接 for i in list
是因为在另一个list中还要用到相同的下标位置,然后 P
也用 range
是因为 P
里边还有 list。
好像按@yooz_hardy所说的用 enumerate
可以解决我的问题了,还有什么更好的方法或者优化建议欢迎指出。
现在下标的问题已经弄清楚了,但是有关我这个多边形拓扑关系建立的作业又有了别的问题:
A=['S3','S2','S1']
B=['S4','S6','S1']
C=['S2','S5','S4']
D=['S3','S6','S5']
N=[A,B,C,D] #节点表,每个点记录顺时针方向排序的弧段
N0=['A','B','C','D'] #节点的字符表
S1=['A','B']
S2=['C','A']
S3=['D','A']
S4=['B','C']
S5=['C','D']
S6=['B','D']
S=[S1,S2,S3,S4,S5,S6] #弧段表,每个弧段含有起始点和终点
S0=['S1','S2','S3','S4','S5','S6'] #弧段的字符表
P=[]
def du(Si,P): #定义弧段的‘度’,弧段属于一个多边形度就加一
d=0
for Pi in P:
if Si in Pi:
d=d+1
return d
for i,Si in enumerate(S0):
for j,Nj in enumerate(N0):
if du(Si,P)==1: #如果某弧段度等于1,将其从弧段表中删去
S0.remove(Si)
S.remove(S[i])
elif du(Si,P)==2: #如果某弧段度等于2,将其从节点的弧段排序中删去
N[j].remove(Si)
else:
Pc=[Si] #建立当前多边形
Sc=Si #当前边
Ns=S[i][0] #起点
Nc=S[i][1] #当前点
while Ns != Nc:
k=N0.index(Nc)
p=N[k].index(Sc) #寻找当前点字符对应的节点,并在结点表中找到当前边位置
p1=p+1 #当前边在表中下一条边的位置
if p1 > len(N[k]):
i_p1=0
Sc=N[k][p1] #把下一条边设为当前边
Pc.append(Sc) #把新的当前边加入多边形中
n=S0.index(Sc)
Nc=S[n][1] #新当前点
P.append(Pc) #起点终点重合时将当前多边形放入多边形组中
问题:
1.忽略了左多边形和右多边形,左多边形的新当前点为S[n][1]
,右多边形新当前点为S[n][0]
,这个可以先做个if
看原本的当前点在新的当前弧中的位置,再确定是左还是右
2.但是多边形组'P'的结构不知道怎么设置比较好,如果在每个多边形里再分L
,R
两个分组会不会太复杂(起始边可以默认放在左多边形里)
3.节点表和弧段表每个都有对应的字符表,下边运算的时候还要找相应位置进行处理,挺麻烦,有没有什么函数直接把list的子集名变为字符?或者有什么更好的结构?
Based on the current information, the following may be a writing method you can refer to:
Several other people have given a lot of useful suggestions. Another suggestion I have is to try to give meaningful names when naming variables, so that people who read the code will understand what you mean more quickly.
P.S. Looking at your initial question, I found that you may not be very familiar with Python’s function definitions, calls and parameters, etc. It is recommended that you take this opportunity to understand it. If there is anything you feel unclear, you can try to ask here Be clear, everyone will help you, good luck!
The questioner may not understand the difference between formal parameters and actual parameters
Try to avoid defining functions in loops.
range(len(blabla)) is not a pythonic way of writing.
The list in python itself supports iteration, you can "for i in LIST"
You can use "list analysis" to simplify the code.
Variable name/function name....I can’t understand it.
Brother, there must be something wrong with your logic.
Or you can try to directly bring the serial number when traversing the list:
Just pass i in directly
The variable name is a bit confusing