2015-11-13 73 views
0

我想循环遍历一个集合Group并获取该集团的最后一个值。如何遍历一个集合并获取集合的最后一个值

我尝试以下的代码:

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

而我的结果如下:

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

在上面的代码中,我已经采用了一系列(1,6)作为一个例子,但在现实中我不会”吨知道范围编号,所以我想写的代码,不使用range/xrangeprint

尽管代码是用Python编写的,但我的问题更一般。

+1

最后一个元素可以用'm [-1]'得到吗?在你的代码中,你将'set'附加到'm',但是'set'没有被定义,只要我能看到 –

+0

对不起,它没有设置,它是组 –

回答

0
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 
+0

对不起,这里的问题得到了设置becoz我不知道如何定义设置,它可能有很多元素 –

+0

@Agastya Peela,咦?你的问题是:*我想循环一个集合,并获得集合的最后一个值。 – 7stud

+0

我认为问题在于他必须首先生成列表。从列表中获取最后一项。 – Glaslos

2

你的代码没有多大意义。

m.append(set) 

没有做任何事情,它只是追加蟒蛇类型setm,而不是你从base.Getentity

但是回到刚才的问题中获得的价值。

你可以尝试使用while循环。

像这样:

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]) 
+0

它不工作的结果是None,m =无 –

+0

一组可以有None作为一个元素。 – 7stud

+0

谢谢你,它与i = 1一起工作 –

0

我喜欢这个简单的迭代解决方案可能会做你的工作:

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 
+0

'i'没有被定义;) –

+0

如果i + = 1不是必需的,如果返回值是None,那么可以通过执行i + = x来提高效率,如果它不是None,那么我= - x/2 ,我+ = x/4等等...... :) – Glaslos

+0

是啊,我没有定义,我不知道定义 –

0

假设i是未知的,你必须遍历i让你最终结果:

生成你的价值观和打印最后:

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 

我们没有跟上的结果列表,因此保持低内存占用,如果i可能很大。