Agastya Peela
Agastya Peela

Reputation: 23

How to loop through a set and get the last value of set

I want to Loop through a set named Group and get the last value of the Group.

I tried the following code:

m = list()
for i in range (1,6):
    Group = base.Getentity(constants.ABAQUS, "SET", i)
    m.append(Group)
    print(Group)

And my result is following:

<Entity:0*17a:id:1>
<Entity:0*14g:id:2>
<Entity:0*14f:id:3>
<Entity:0*14a:id:4>
None
None

In the above code I have used a range of (1,6) as an example but in reality I wouldn't know the range number so I'd like to write code such that doesn't use range/xrange or print.

Even though the code is written in Python my question is more general.

Upvotes: 0

Views: 260

Answers (4)

Glaslos
Glaslos

Reputation: 2923

Assuming i is unknown and you have to iterate over i to get you final result:

Generating your values and printing the last:

i = 1
last_group = None
while True:
    group = base.Getentity(constants.ABAQUS,"SET", i)
    if not group:
        print 'Last item: {0} with i: {1}'.format(last_group, i)
    last_group = group
    i += 1

We are not keeping a list of results therefore keep a low memory footprint if i can be large.

Upvotes: 0

f.rodrigues
f.rodrigues

Reputation: 3587

Your code doesn't make lot of sense.

m.append(set)

is not doing anything, it just appends the python-class-type set to the m, not the value you get from base.Getentity

But back to the question.

You could try using a while loop.

Like so:

m = []
i = 0
while True:
   group = base.Getentity(constants.ABAQUS,"SET",i)
   if group is None:
       break
   i += 1
   m.append(group)
print(m[-1])

Upvotes: 2

7stud
7stud

Reputation: 48609

my_set = {1, 'hello', 12.4}
print(my_set)
print(list(my_set).pop())

--output:--
{1, 12.4, 'hello'}
hello

my_set = {1, 'hello', 12.4}
print(my_set)

while True:
    try: 
        val = my_set.pop()
        print(val)
    except KeyError:
        print("last: {}".format(val))
        break

--output:--
{1, 12.4, 'hello'}
1
12.4
hello
last: hello

Upvotes: 0

Kon Pal
Kon Pal

Reputation: 574

I simple iterative solution like this probably could do your job:

last_group = None
i = 0
while True:
    next_group = base.Getentity(constants.ABAQUS, "SET", i)
    i += 1
    if next_group is None:
        break
    last_group = i, next_group

print last_group

Upvotes: 0

Related Questions