开发者

Print set() item fill with python generator

I have a 开发者_StackOverflow社区generator:

foundUnique = set()
def unique_items(myList, index, clearFlag): 
    for item in myList:
        if clearFlag is True:
            foundUnique.clear()
            clearFlag = False
        if item[index] not in foundUnique:
            yield item
            foundUnique.add(item[index])

And I am using this `unique_items to get a unique list:

senderDupSend = unique_items(ip, 4, True)

Now I want my set to be reachable (I can print its element or do some changes on specific element .....) but when I write:

for item in foundUnique:
    print item

It prints nothing!

But if I write:

for item in senderDupSend:
    print item
for item in foundUnique:
    print item

It prints all foundUnique items.

Please tell what did I do wrong? How can I solve this problem?


The problem is that unique_items is a generator so that

senderDupSend = unique_items(ip, 4, True)

is a generator that needs to be iterated over. When you run

for item in foundUnique:
    print item

the generator has not actually run yet so foundUnique is still empty.

When you later go on to do

for item in senderDupSend: # This is what actually fills the list.
    print item
for item in foundUnique:
    print item

It should print out the set twice: once while it is being constructed and once after it is constructed.


It seems like what you are trying to do is construct a set that has the same index taken from every element of some sequence. You can do it like this very easily:

found_unique = set(item[index] for item in sequence)

In the concrete case that you show, it would be:

found_unique = set(item[4] for item in ip)

If you later wanted to extend the set to contain other items, you could do

found_unique.union(item[4] for item in other_ip_list) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜