简体   繁体   English

从列表元素python中删除括号

[英]removing brackets from list elements python

I am a python newbie; 我是python新手; it is highly likely someone has asked a similar question, though I can't find one. 尽管我找不到,但很可能有人问了类似的问题。 When I query for objects from a model created in another program I get a list like this: 当我从另一个程序中创建的模型中查询对象时,会得到如下列表:

lineObj = [obj for obj in model.objects if obj.type == OF.otLine]

print lineObj
[<Line: 'Upper1'>, <Line: 'Upper2'>, <Line: 'MooringLine'>, <Line: 'BuoyLine'>, <Line: 'RiserLine1'>, <Line: 'RiserLine2'>, <Line: 'AnchorLine1'>, <Line: 'AnchorLine2'>, <Line: 'AnchorLine3'>]

print lineObj[0] 
<Line: 'Upper1'>

I would like to be able to pull only the text Upper1, Upper2, etc., but I am not sure how. 我只想拉文本Upper1,Upper2等,但是我不确定如何拉。 It may be better to use a dictionary or something else. 使用字典或其他方法可能更好。 Thanks in advance for any feedback. 预先感谢您的任何反馈。

If print str(lineObj[0]) produces the string <Line: 'Upper1'> as listed in the comments, this should work to clean up your list: 如果print str(lineObj[0])生成字符串<Line: 'Upper1'>如注释中所列,这应该可以清理您的列表:

lineObj = [str(item).split("'")[1] for item in lineObj]

print lineObj[0] now produces Upper1 print lineObj[0]现在产生Upper1

You are getting <Line: 'Upper1'> because that is how the object's __str__ function is formatted. 您将得到<Line: 'Upper1'>因为这是对象的__str__函数的格式。

The best way to get the result you want would be to figure out what attribute of the object you are looking for. 获得所需结果的最佳方法是弄清楚您要查找的对象的属性。 In this case, that is name . 在这种情况下,即name

lineObj = [obj.name for obj in model.objects if obj.type == OF.otLine]

print lineObj
>>> ['Upper1', 'Upper2', 'MooringLine', 'BuoyLine', 'RiserLine1', 'RiserLine2', 'AnchorLine1', 'AnchorLine2', 'AnchorLine3']

print lineObj[0]
>>> 'Upper1'

I'm guessing you are using OrcaFlex and your actual problem is getting the names of the Line objects. 我猜您正在使用OrcaFlex,而您的实际问题是获取Line对象的名称。

A relatively recent version of the pyoxf API will contain some helpers for retrieving the lines and the example in the doc indicates the name is available as the "name" property: pyoxf API的相对较新版本将包含一些用于检索行的帮助程序,并且doc中的示例表明该名称可用作“ name”属性:

lineNames = [lineObject.name for lineObject in model.lines]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM