'Is it possible to create array of variables in a python for loop?
I am trying to play around the elements of a list. For instance, I have a list like
list = ["zone", "abigail", "theta", "form", "libe", "zas"]
Now I want to create a for loop and assign different words to different variables in the loop like...
word = ""
length = 0
for e in range(len(list)):
word[e] = list[e]
length[e] = len(list[e])
print " The word '%s' and its length is %d " %(word[e], length[e])
I am now expecting the array of variables
word[1] = 'zone'
word[2] = 'abigail' .... and so on.
Is this possible in python?
Solution 1:[1]
Variable word is a str not a list. Don't try to index it! The same with length, it is an int variable!
You should use:
word = list[e]
length = len(list[e])
Also, avoid using list as a variable name, as it shadows the built-in type.
Edit:
If you want all words in a list at the end you can use list variable declared at the start. If you want all the lengths stored in a list, change lengths = 0 for lengths = [] and append each length in the for loop (lengths.append(len(list[e]))
Solution 2:[2]
You don't really need a for loop
lst = ["zone", "abigail", "theta", "form", "libe", "zas"]
word = lst[:]
length = list(map(len, word))
Solution 3:[3]
Why not build a dictionary instead?
a_list = ["zone", "abigail", "theta", "form", "libe", "zas"]
my_dict = {k: len(k) for k in a_list}
Then you can use it like this:
for kk, vv in my_dict.iteritems():
print("The word '{}' has lenght: {}".format(kk, vv))
If you want to concatenate the two longest words, then you can sort the dictionary by value, i.e.:
import operator
sorted_dict = sorted(my_dict.items(), key=operator.itemgetter(1), reverse=True)
And then concatenate the first results:
sorted_dict[0][0] + sorted_dict[1][0]
This results in:
>>> 'abigailtheta'
Granted, for that case I agree using lists results in a much simpler syntax.
Solution 4:[4]
No, there is no such function. The search process stops as soon as a constraint is unsatisfiable or as soon as a constraint has emptied the domain of a variable. Therefore, whenever a fail happens, there is no guarantee whatsoever on the variables' domains, which make things difficult to retrieve the list of unsatisfied constraints. The best you can do is to retrieve the list of propagators and check their status using the isEntailed() function.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Carles Mitjans |
| Solution 2 | OneCricketeer |
| Solution 3 | |
| Solution 4 | Arthur Godet |
