Python For loops Creating Diffrent Lists - python

I have an idea but don't know how to execute it.
i have a variable value EG: 5
now i want my python program to create 5 different list all with differnt names
EG: list1 = []
list2 = []
...

I don't know if this is possible. When you say list1, you mean that list1 is an identifier for a variable which is a list. I don't think it is possible that the program creates identifiers within itself (or at least I don't know how).
Of course, you can write a Python program which writes another Python program where there are variables with these identifiers, then get creative with it:
VAL = 5 # can change this
f = open("lists.py", "w")
for i in range(1, VAL + 1):
f.write("list" + str(i) + " = []\n")
f.close()
Output (lists.py):
list1 = []
list2 = []
list3 = []
list4 = []
list5 = []

Morning Jacob,
I have a little bit of difficulties reading your question. But let me try to answer your question.
Direct answer
There are no simple way to generate python variables. The only way I know is to generate the code as str and then execute it.
def generate_code(n):
ret = ""
for i in range(1, n + 1):
var_name = "lst_" + str(i)
ret += var_name + " = []\n"
return ret
code = generate_code(5)
print(code)
exec(code)
where the printed code will be
lst_1 = []
lst_2 = []
lst_3 = []
lst_4 = []
lst_5 = []
The idiomatic solution
The idiomatic solution would be to create a list of list. Something like bellow.
lsts = [[] for i in range(5)]
then, you could access your sub lists using indexes in a very similar fashion then with the variables you asked for. lsts[0] would be equivalent of the above lst_1, lsts[1] would be equivalent of the above lst_2, lsts[2] would be equivalent of the above lst_3, ...

Related

how to assign variables in another variable in python?

I need to have different results for different "i"s
so whenever i call for example a_8, it should return me the exact value. but python
doesnt assign diferrent "i"s to it and just knows a_i.
1.for i in range(10): a_i = i + 5
You can use a list:
a = []
for i in range(10): a.append(i+5)
or a dictionary:
a = {}
for i in range(10): a[i] = i+5
In both cases, you can access the value later with
for i in range(10): print(a[i])
What I should use on my case?
Take a look at this answer.
for i in range(10):
globals()['a_' + str(i)] = i + 5
print(a_6)
but i don't think you should use it, better use dicts instead.

How to use data from one function in another function?

I am a beginner and had a question related to using function data with other functions.
Say that a function my_list generates a list as well as a sublist. I want to know how to access items from the sublist of that list generated by the function and use the numbers to compute a sum of them in the other function. I have tried things like
def compute_sum(myNewlist): #myNewList is the list generated by the other function#
for i in myNewList:
addup += i
but I really am not well versed enough yet in python to think about how to do this. I guess what I am asking is how to call elements in a sublist to another function?
edit - just going to drop the code here for more understanding from repliers!
fyle = input('Enter the file name you want to process: ')
def read_data(fyle):
with open(fyle) as file:
for line in fyle:
lne = [line.strip().split() for line in open(fyle).readlines()]
newlist = [[elem[1], elem[0], elem[2]] for elem in lne]
print(newlist)
read_data(fyle)
def compute_sum(newlist):
???
edit 2 - also the list looks like
mylist = [[Smith, Bob, 18], [Jorgen, Peter, 14]] - to this, i am looking to extract and add the numbers, not the strings
Here's an example rewrite of your code that I think demonstrates what you're asking:
fyle = input('Enter the file name you want to process: ')
def read_data(fyle):
lne = [line.strip().split() for line in open(fyle).readlines()]
newlist = [[elem[1], elem[0], elem[2]] for elem in lne]
return newlist
def compute_sum(newlist):
s = sum([int(x[0]) for x in newlist])
return s
list = read_data(fyle)
sum = compute_sum(list)
print(sum)
Data file /tmp/data.txt:
line1_item1 10 line1_item3
line2_item1 20 line2_item3
line3_item1 30 line3_item3
Result:
Enter the file name you want to process: /tmp/data.txt
60
The below code should work to compute the sum. As mentioned in your post above, I have considered mylist = [[Smith, Bob, 18], [Jorgen, Peter, 14]].
def compute_sum(new_list):
sum=0
for item in new_list:
sum=sum+int(item[2])
#print(sum)
return sum

How to create a list from a string inside another list. Python? [duplicate]

This question already has answers here:
How to declare many variables?
(5 answers)
Closed 2 years ago.
I was thinking is there a way to take a string that is in a list and convert it to list in python? For example, I have a list: teams = ['team_one', team_two', team_three,]. How do I get three separate empty lists from it?
team_one = []
team_two = []
team_three = []
Thank you!
You are talking about dynamically creating variables. Ideally you should not be doing this and use typical data structures instead.
If you had to you could do something like this
for name in teams:
globals()[name] = 0
for i in range(10):
globals()['variable{}'.format(i)] = 0
For more information as to why this is a bad idea check out this link
below is a slightly easier to understand code but also still a bad idea.
>>> name = input("Enter a variable name: ")
Enter a variable name: X
>>> globals()[name] = 42
>>> X
42
This is not a good idea in common ways, but if forced, you can do:
>>> teams = ['team_one', 'team_two', 'team_three']
>>> for i in teams:
... exec(i + ' = []')
...
>>> team_one
[]
>>> team_two
[]
>>> team_three
[]
You can use a for loop to add to a dictionary (or create a dictionary with list comprehension, as #Blotosmetek commented). Both do the same thing.
d = {}
for item in teams:
d[item] = []
EDIT:
In hindsight, a for loop can just be used to create the variables with no need for a dictionary.
for item in teams:
item = []

Is it possible to use the same slice notation in both a list and an element to get the same result?

I want to get the element in the last index of a list, but sometimes the last index is a list, in this case I want the first element in the nested list.
#list in moment 1:
Lm1 = [1,2,3,4]
#list in moment 2:
Lm2 = [1,2,3,4,[1,2,3]]
I can just use an if for this.
#Option1:
def if_list(lastposition):
if isinstance(lastposition, list):
return list[0]
else:
return lastposition
element = if_list(Lm1[-1])
do whatever
Or if I want to do the same operation in both cases I could buit the list like this and use the same slice notation. It will give the element I want.
#Option2:
Lm1 = [[1],[2],[3],[4]]
Lm2 = [[1],[2],[3],[4],[1,2,3]]
Lm1[-1][0]
Lm2[-1][0]
Is there a way to do this using something similar to slice notation that will work in both cases (when index is list and when index is not list) or a simple one liner?
Something like:
#Lm1[-1:][:]...
The problem is that I don't know if its more time eficient to just build the list
like Option2 and use the same slice notation or to use the if cause everytime like Option1.
I'm using pythom 3.7, don't know much about older versions.
I created a test bench to compare using try-except and isinstance to see which is faster and here are the results.
Option2:
Parsing all data to a list doesn't seem like an efficient way to me. :/
import time, statistics
Lm2 = [1,2,3,4,1,2,3]
t = []
for y in range(4):
s = time.time()
for i in range(100000):
if isinstance(Lm2[-1], list):
x = Lm2[-1][0]
else:
x = Lm2[-1]
t.append(time.time() - s)
print(statistics.mean(t))
Lm2 = [1,2,3,[4,1,2,3]]
t = []
for y in range(4):
s = time.time()
for i in range(100000):
try:
x = Lm2[-1][0]
except Exception:
x = Lm2[-1]
t.append(time.time() - s)
print(statistics.mean(t))
Lm2 = [1,2,3,[4,1,2,3]]
t = []
for y in range(4):
s = time.time()
for i in range(100000):
x = Lm2[-1][0] if type(Lm2[-1]) is list else Lm2[-1]
t.append(time.time() - s)
print(statistics.mean(t))
The results as follow in order
# When the last element is a list
# 0.024208366870880127
# 0.011709034442901611
# 0.03266298770904541
# When the last element is an int
# 0.02896404266357422
# 0.015629112720489502
# 0.03452497720718384
According to the data I got, using try-except will be always faster
You can do a one liner like this if you want:
#list in moment 1:
Lm1 = [1,2,3,4]
#list in moment 2:
Lm2 = [1,2,3,4,[1,2,3]]
def test(test_list):
return test_list[-1][0] if type(test_list[-1]) is list else test_list[-1]
print(test(Lm1))
print(test(Lm2))
Check if the last value is a list, if it is, return the first value, otherwise give you the last element of your list.

what's the difference between two kinds of iteration of list

Here is my code
i got two different output which are [2] and [2,4,6], can someone do some explanation?
list = [1,2,3]
def getdouble(l):
result = []
for i in l :
i = i * 2
result.append(i)
return result
print getdouble(list)
def getdouble_v2 (l):
result = []
for i in range(len(l)):
l[i] = l[i] * 2
result.append(l[i])
return result
print getdouble_v2(list)
The only way to get the output you claim is if the indentation in your file is broken. Verify that you're not mixing spaces and tabs with python -tt.
Both functions return the same result list for the same input list. However the second function modifies the original list as well in the line l[i] = l[i] * 2. The first function does not.
So, the results for the first function are:
l = [1,2,3]
result = [2,4,6]
The results for the second function are:
l = [2,4,6]
result = [2,4,6]
You are using 4 spaces for indentation except for the line
return result
which is indented by a tab. This is unfortunate because your editor shows the tab as 4 spaces, but Python treats it as 8 spaces, so the code looks like this to Python
list = [1,2,3]
def getdouble(l):
result = []
for i in l :
i = i * 2
result.append(i)
return result
So you see, it's returning after the first item is appended to the list

Categories

Resources