简体   繁体   中英

removing brackets from list elements python

I am a python newbie; 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. 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:

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

print lineObj[0] now produces Upper1

You are getting <Line: 'Upper1'> because that is how the object's __str__ function is formatted.

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 .

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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