Find all index position in list based on partial string inside item in list
You can use enumerate inside a list-comprehension: indices = [i for i, s in enumerate(mylist) if ‘aa’ in s]
You can use enumerate inside a list-comprehension: indices = [i for i, s in enumerate(mylist) if ‘aa’ in s]
On top of the already provided answers there is a very nice pattern in Python that allows you to enumerate both keys and values of a dictionary. The normal case you enumerate the keys of the dictionary: example_dict = {1:’a’, 2:’b’, 3:’c’, 4:’d’} for i, k in enumerate(example_dict): print(i, k) Which outputs: 0 1 1 … Read more
I would use enumerate as it’s more generic – eg it will work on iterables and sequences, and the overhead for just returning a reference to an object isn’t that big a deal – while xrange(len(something)) although (to me) more easily readable as your intent – will break on objects with no support for len…
Use itertools.product. from string import ascii_lowercase import itertools def iter_all_strings(): for size in itertools.count(1): for s in itertools.product(ascii_lowercase, repeat=size): yield “”.join(s) for s in iter_all_strings(): print(s) if s == ‘bb’: break Result: a b c d e … y z aa ab ac … ay az ba bb This has the added benefit of going … Read more
Yes, absolutely. Using Reflection: static IEnumerable<Type> GetTypesWithHelpAttribute(Assembly assembly) { foreach(Type type in assembly.GetTypes()) { if (type.GetCustomAttributes(typeof(HelpAttribute), true).Length > 0) { yield return type; } } }
This post is relevant here https://www.swift-studies.com/blog/2014/6/10/enumerating-enums-in-swift Essentially the proposed solution is enum ProductCategory : String { case Washers = “washers”, Dryers = “dryers”, Toasters = “toasters” static let allValues = [Washers, Dryers, Toasters] } for category in ProductCategory.allValues{ //Do something }
This will work for general reading a String from Text. If you would like to read longer text (large size of text), then use the method that other people here were mentioned such as buffered (reserve the size of the text in memory space). Say you read a Text File. NSString* filePath = @””//file path… … Read more
The enumerate() function adds a counter to an iterable. So for each element in cursor, a tuple is produced with (counter, element); the for loop binds that to row_number and row, respectively. Demo: >>> elements = (‘foo’, ‘bar’, ‘baz’) >>> for elem in elements: … print elem … foo bar baz >>> for count, elem … Read more