【问题标题】:Returning list indices from a dictionary value [duplicate]从字典值返回列表索引[重复]
【发布时间】:2020-03-17 21:20:29
【问题描述】:

有没有一种从字典值中提取列表索引的简单方法?

Central_Bonds_Cyclo = { 'A1-A2' : [A1,A2], 'A1-A4' : [A1,A4], 'A2-A3' : [A2,A3], 'A3-A4' : [A3,A4] }

假设我想将每两个成员列表传递给一个函数:

CycloButadiene += LineSegment( A1, A2, 1, color = 'white' )
CycloButadiene += LineSegment( A1, A4, 1, color = 'white' )
CycloButadiene += LineSegment( A2, A3, 1, color = 'white' )

这就是我目前的做法:

def bond_split(AxAy):
    x = AxAy[0]
    y = AxAy[1]
    return(x,y)
for bond in Central_Bonds_Cyclo:
        Benzene += LineSegment(bond_split(Central_Bonds_Cyclo[bond])[0],
        bond_split(Central_Bonds_Cyclo[bond])[1], 1, color = 'white' )

有没有更优雅的方法来解决这个问题?

【问题讨论】:

    标签: python list dictionary sage


    【解决方案1】:

    您可以通过* 语法使用参数解包:

    for key, value in Central_Bonds_Cyclo.items():
        Benzene += LineSegment(*value, 1, color='white')
    

    【讨论】:

      猜你喜欢
      • 2020-04-18
      • 2019-08-01
      • 1970-01-01
      • 2021-01-31
      • 2019-12-31
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多