def main():
my_list = [[float(i) for i in line.split(',')] for line in open("Alpha.txt")]
print(my_list)
for elem in my_list:
listA=[]
listA = elem
print(listA)
main()
this code prints out the correct data of which im looking for, however i need to set each print from the for loop into a object. Any help as to how i would go about doing that?
[1.2, 4.3, 7.0, 0.0]
[3.0, 5.0, 8.2, 9.0]
[4.0, 3.0, 8.0, 5.6]
[8.0, 4.0, 3.0, 7.4]
What you're thinking of/trying to do is to dynamically name variables.
Don't.
Either leave your data in the list and access it via index
my_list[0] #what you were trying to assign to 'a'
my_list[0][0] #the first element in that sub-list
Or, if you have meaningful identifiers that you want to assign to each, you can use a dict to assign "keys" to "values".
d = {}
for sublist, meaningful_identifier in zip(my_list, my_meaningful_identifiers):
d[meaningful_identifier] = sublist
Either way, leverage python data structures to do what they were supposed to do.
This is not a good idea, let me warn you, and you should never use this in production code (it is prone to code injection), and screws up your global namespace, but it does what you asked.
You would use exec() for this, which is a function that dynamically executes statements.
def main():
my_list = [[float(i) for i in line.split(',')] for line in open("Alpha.txt", "r")]
print(my_list)
for elem in my_list:
exec "%s = %s" % ("abcdefghijklmnopqrstuvwxyz"[my_list.index(elem)], elem) in globals()
main()
Now, your global namespace is filled with variables a, b, c, etc. corresponding to the elements.
It is also prone to exceptions, if you have more than 26 elements, you will get an IndexError, although you could work around that.
Try:
myList = [map(float, line.split(',')) for line in open ("Alpha.txt")]
Now you can get each line in a different variable if you want:
a = myList[0]
b = myList[1]
and so on. But since you have a list, it's better to use it and access elements using indices. Are you sure have a correct understanding of arrays?
As the other answers point out, it is dangerous and doesn't make sense to dynamically create variables.
Related
Can someone explain the last line of this Python code snippet to me?
Cell is just another class. I don't understand how the for loop is being used to store Cell objects into the Column object.
class Column(object):
def __init__(self, region, srcPos, pos):
self.region = region
self.cells = [Cell(self, i) for i in xrange(region.cellsPerCol)] #Please explain this line.
The line of code you are asking about is using list comprehension to create a list and assign the data collected in this list to self.cells. It is equivalent to
self.cells = []
for i in xrange(region.cellsPerCol):
self.cells.append(Cell(self, i))
Explanation:
To best explain how this works, a few simple examples might be instructive in helping you understand the code you have. If you are going to continue working with Python code, you will come across list comprehension again, and you may want to use it yourself.
Note, in the example below, both code segments are equivalent in that they create a list of values stored in list myList.
For instance:
myList = []
for i in range(10):
myList.append(i)
is equivalent to
myList = [i for i in range(10)]
List comprehensions can be more complex too, so for instance if you had some condition that determined if values should go into a list you could also express this with list comprehension.
This example only collects even numbered values in the list:
myList = []
for i in range(10):
if i%2 == 0: # could be written as "if not i%2" more tersely
myList.append(i)
and the equivalent list comprehension:
myList = [i for i in range(10) if i%2 == 0]
Two final notes:
You can have "nested" list comrehensions, but they quickly become hard to comprehend :)
List comprehension will run faster than the equivalent for-loop, and therefore is often a favorite with regular Python programmers who are concerned about efficiency.
Ok, one last example showing that you can also apply functions to the items you are iterating over in the list. This uses float() to convert a list of strings to float values:
data = ['3', '7.4', '8.2']
new_data = [float(n) for n in data]
gives:
new_data
[3.0, 7.4, 8.2]
It is the same as if you did this:
def __init__(self, region, srcPos, pos):
self.region = region
self.cells = []
for i in xrange(region.cellsPerCol):
self.cells.append(Cell(self, i))
This is called a list comprehension.
I am attempting to index a list to pull the first (0) and second (1) items for further calculations. My code currently looks like this:
def calculate_scores(list):
sat = list[0]
gpa = list[1]
weighted_sat = (sat / 160)
weighted_gpa = (gpa * 2)
This is in the function that I want to use to do the calculations. The part where this function is called in my main looks like this:
testscores = []
semestergrades = []
testscores.append(floatlist[0:4])
semestergrades.append(floatlist[4:])
calculate_scores(testscores)
The list that the testscores list is pulling from is 8 items long, all of them floats - however, when I try to run this code it gives me a 'list index out of range' error for the part where I try to set the variable 'gpa' equal to list[1]. However, it seems to be able to run the first part, setting the variable 'sat' equal to list[0]. Any idea why this is happening?
You're using .append() when you should either be using .extend() or just using the result of the slice:
# floatlist = [0.5, 1.5, 2.5, 3.5, 4.5, 5.5]
testscores = []
testscores.append(floatlist[0:4])
# testscores = [[0.5, 1.5, 2.5, 3.5]]
So, how you're currently doing it, testscores is a list with one element, that element being floatlist[0:4]. When you try to use the second element (index 1), you get an IndexError.
You can use .extend() instead of .append() to add all the items in the given iterable to the list. Or, you could just do
testscores = floatlist[0:4]
since list slicing produces a copy of the original anyway.
In the following code I want to check how many unique values are in the list and this can be done in for loop. After knowing the number of unique values I want to see how many times a single unique values appear in a and then I want to count their number. Can someone please guide me how to do that. List contains floating points. What if I convert it in numpy array and then find same values.
`a= [1.0, 1.0, 1.0, 1.0, 1.5, 1.5, 1.5, 3.0, 3.0]
list = []
for i in a:
if i not in list:
list.append(i)
print(list)
for j in range(len(list))
g= np.argwhere(a==list[j])
print(g)`
You can use np.unique to get it done
np.unique(np.array(a),return_counts=True)
You can also do it using counters from collections
from collections import Counter
Var=dict(Counter(a))
print(Var)
The primitive way is to use loops
[[x,a.count(x)] for x in set(a)]
If you are not familiar with list comprehensions, this is its explaination
ls=[]
for x in set(a):
ls.append([x,a.count(x)])
print(ls)
If you want it using if else,
counter = dict()
for k in a:
if not k in counter:
counter[k] = 1
else:
counter[k] += 1
print(counter)
This question already has answers here:
How to print column in python array?
(2 answers)
Closed 5 years ago.
I have the following list:
[[50.954818803035948, 55.49664787231189, 8007927.0, 0.0],
[50.630482185654436, 55.133473852776916, 8547795.0, 0.0],
[51.32738085400576, 55.118344981379266, 6600841.0, 0.0],
[49.425931642638567, 55.312890225131163, 7400096.0, 0.0],
[48.593467836476407, 55.073137270550006, 6001334.0, 0.0]]
I want to print the third element from every list. The desired result is:
8007927.0
8547795.0
6600841.0
7400096.0
6001334.0
I tried:
print data[:][2]
but it is not outputting the desired result.
Many way to do this. Here's a simple list way, without an explicit for loop.
tt = [[50.954818803035948, 55.49664787231189, 8007927.0, 0.0], [50.630482185654436, 55.133473852776916, 8547795.0, 0.0], [51.32738085400576, 55.118344981379266, 6600841.0, 0.0], [49.425931642638567, 55.312890225131163, 7400096.0, 0.0], [48.593467836476407, 55.073137270550006, 6001334.0, 0.0]]
print [x[2] for x in tt]
> [8007927.0, 8547795.0, 6600841.0, 7400096.0, 6001334.0]
And making is safe for potentially shorted lists
print [x[2] for x in tt if len(tt) > 3]
More sophisticated output (python 2.7), prints values as newline (\n) seperated
print '\n'.join([str(x[2]) for x in tt])
> 8007927.0
> 8547795.0
> 6600841.0
> 7400096.0
> 6001334.0
Try this:
for item in data:
if len(item) >= 3: # to prevent list out of bound exception.
print(int(item[2]))
map and list comprehensive have been given, I would like to provide two more ways, say d is your list:
With zip:
zip(*d)[2]
With numpy:
>>> import numpy
>>> nd = numpy.array(d)
>>> print(nd[:,2])
[ 8007927., 8547795., 6600841., 7400096., 6001334.]
Maybe you try a map function
In python 3:
list(map(lambda l: l[2], z))
In python 2:
map(lambda l: l[2], z)
In order to print the nth element of every list from a list of lists, you need to first access each list, and then access the nth element in that list.
In practice, it would look something like this
def print_nth_element(listset, n):
for listitem in listset:
print(int(listitem[n])) # Since you want them to be ints
Which could then be called in the form print_nth_element(data, 2) for your case.
The reason your data[:][2] is not yielding correct results is because data[:] returns the entire list of lists as it is, and then executing getting the 3rd element of that same list is just getting the thirst element of the original list. So data[:][2] is practically equivalent to data[2].
Assume there are a list like following, it is important to note that this is an arbitrary list, to demonstrate that list contains completely random lists with strings/numeric values:
[[["1"],"1"],["2",[["123",[[["23"]]],23],[12.3,"23"]]],[["5"],"1","1"]]
I want to get every single item in this list but I want to get only numbers or strings but not list. Let's say, I created a function which takes only strings, integers and float but not lists. I want to use this function.
I want to create the same list but with different object based on the function's output. Let's say function converts string to numeric value. I want to create a list like that:
[[[1],1],[2,[[123,[[[23]]],23],[12.3,23]]],[[5],1,1]]
I thought and I could not come with an answer. How can I do that?
You probably want to traverse your entire structure recursively, and either store the results or call your function on the results right there. It would look something like this:
sample = [[["1"],"1"],["2",[["123",[[["23"]]],23],[12.3,"23"]]],[["5"],"1","1"]]
def traverse(l, f):
result = []
for item in l:
if isinstance(item, list):
result.append(traverse(item))
else:
result.append(f(item))
return result
Here is a function that resembles a very simple attempt at nested map:
def map_nested(fnc, l):
try:
return fnc(l)
except:
return [map_nested(fnc, sub) for sub in l]
>>> l = [[["1"],"1"],["2",[["123",[[["23"]]],23],[12.3,"23"]]],[["5"],"1","1"]]
>>> map_nested(float, l)
[[[1.0], 1.0], [2.0, [[123.0, [[[23.0]]], 23.0], [12.3, 23.0]]], [[5.0], 1.0, 1.0]]
It will apply the provided function fnc to all items in l that are valid arguments to that function (or to l itself) and attempts to iterate over the others.