【问题标题】:Return a cell array based on string name in it根据其中的字符串名称返回一个元胞数组
【发布时间】:2018-04-08 09:44:44
【问题描述】:
A=[['Upper_lower_torque/SPH-Lower torque-Upper torque.1', 'DynGraphElement', {'fx1': 239761.59375, 'fy1': -121644.0, 'fz1': -299702.0, 'tx1': 0.0, 'ty1': 0.0, 'tz1': 0.0, 'fmg1': 402621.62557113107, 'tmg1': 0.0}], ['Upper_lower_torque/REV--Lower torque.1', 'DynGraphElement', {'fx1': 239761.59375, 'fy1': -121644.0, 'fz1': -299702.0, 'tx1': 30411.0, 'ty1': -0.0, 'tz1': 24328.80078125, 'fmg1': 402621.62557113107, 'tmg1': 38945.08272495708}]

根据分析,例如,我有 2 个关节的力和力矩,分别是球形 (SPH) 和旋转 (REV) 关节。这些通过['关节名称','元素类型',{六力和力矩}]存储在每个单元格中。假设我想返回 SPH 关节(第一个单元格),所以 ['Upper_lower_torque/SPH.., 'DynGraph..',{'fx1':2391...}] 通过搜索它从数组中返回它是特定的名称,因此包含关键字 SPH 和 Lower 或 Upper。

我知道你可以通过搜索

if any("SPH" in s for s in A ):

但我不能让它工作,因为最好我想要更多的关键字,例如 SPH 和 Lower 或 Upper,如果它们在一个单元格中,我希望返回单元格(或单元格索引),所以最终

['Upper_lower_torque/SPH.., 'DynGraph..',{'fx1':2391...}]

有谁知道如何做到这一点非常有效?

提前致谢

【问题讨论】:

    标签: python arrays string


    【解决方案1】:

    你需要提供一个函数来进行布尔比较,这样你就可以将所有东西打包在一起:

    def get_cell_element(data, comp, index=0):
        for element in data:  # for i, element in enumerate(elements) if you need the index
            if comp(element[index]):
                return element
    

    然后您可以通过提供比较功能轻松搜索您的列表(您甚至可以搜索不同的索引),例如:

    A = [
        ['Upper_lower_torque/SPH-Lower torque-Upper torque.1',
         'DynGraphElement',
         {'fx1': 239761.59375, 'fy1': -121644.0, 'fz1': -299702.0,
          'tx1': 0.0, 'ty1': 0.0, 'tz1': 0.0, 'fmg1': 402621.62557113107, 'tmg1': 0.0}
         ],
        ['Upper_lower_torque/REV--Lower torque.1',
         'DynGraphElement',
         {'fx1': 239761.59375, 'fy1': -121644.0, 'fz1': -299702.0,
          'tx1': 30411.0, 'ty1': -0.0, 'tz1': 24328.80078125, 'fmg1': 402621.62557113107,
          'tmg1': 38945.08272495708}
         ]
    ]
    
    element = get_cell_element(A, lambda x: "SPH" in x and ("Lower" in x or "Upper" in x))
    # ['Upper_lower_torque/SPH-Lower torque-Upper torque.1', 'DynGraphElement',
    #  {'ty1': 0.0, 'fx1': 239761.59375, 'tmg1': 0.0, 'fz1': -299702.0,
    #   'tz1': 0.0, 'fy1': -121644.0, 'tx1': 0.0, 'fmg1': 402621.62557113107}]
    
    element = get_cell_element(A, lambda x: "Lower" in x and "REV" in x)
    # ['Upper_lower_torque/REV--Lower torque.1', 'DynGraphElement',
    #  {'fx1': 239761.59375, 'fz1': -299702.0, 'tz1': 24328.80078125, 'fmg1': 402621.62557113107,
    #   'tmg1': 38945.08272495708, 'ty1': -0.0, 'fy1': -121644.0, 'tx1': 30411.0}]
    # etc.
    

    【讨论】:

    • 这很清楚!非常感谢您的精彩解释,它真的很有帮助!
    猜你喜欢
    • 1970-01-01
    • 2011-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-23
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多