Hello, I am using a for loop to iterate through an array and need to assign each iteration to a new variable, such as -
arr = ['bread', 'milk', 'cheese']
-
for i in arr:
-
print i
-
but instead of printing i, I want the for lopp to assign each iteration to a unique variable, so that when the for loop completes -
var1 = 'bread'
-
var2 = 'milk'
-
var3 = 'cheese'
-
I will use these variables later on in the script. I will not always know how many items are in the array and need the script to generate a new variable for each iteration. Any ideas?
5 42158 bvdet 2,851
Recognized Expert Moderator Specialist
One way is to encapsulate the variables in an object. - class Vars(object):
-
-
def __init__(self, *args):
-
for i, value in enumerate(args):
-
setattr(self, "var%s" % (i), value)
-
-
def get(self):
-
return self.__dict__
-
-
obj = Vars("milk", "bread", "cheese")
-
print obj.get()
Output: >>> {'var1': 'bread', 'var0': 'milk', 'var2': 'cheese'} dwblas 626
Recognized Expert Contributor
You already have that capability with a list. No alteration necessary: - a_list = ['bread', 'milk', 'cheese']
-
print a_list[1] ## instead of var2
-
-
for ctr in len(a_list):
-
print ctr, a_list[ctr]
bvdet 2,851
Recognized Expert Moderator Specialist
I think he is really wanting this: - >>> for i, value in enumerate(["milk", "bread", "cheese"]):
-
... exec "var%s=value" % (i)
-
...
-
>>> var1
-
'bread'
-
>>>
Yes, that is exactly what I was looking for. Thank you much!!
After you get all the variable var1, var2, var3, how would you store them in a list?
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: Christopher Benson-Manica |
last post by:
I have a situation something like this:
int foo;
for( foo=bar() ; foo <= bar()+1 ; foo++ ) {
if( !baz(foo) ) break;
/* do stuff with foo */
}
The idea is that the loop happens at most twice - once for foo=bar(), and once
|
by: paulw |
last post by:
Hi
I have a question:
main() { static int i;
printf("%d\n",i); // should I see see 0 or 5 ???
for (i=5;i<=15;i++) {...} // What's the meaning of static
variable in
|
by: Mike Mac |
last post by:
Hello all,
I have a loop and would like to create a new textbox on each iteration of
the loop. The code below only generates one textbox no matter how many times
the loop loops! Any insight would be greatly appreciated.
int over = 25;
int down = 0;
for (int i = theEmail.Attachments.Count; i > 0; i--)
|
by: david |
last post by:
I try to use "for" loop to assign textbox control ID to a textbox variable in
server side codebehind for a web form. But I met some problem.
What I want to do is solving the following-like code by a loop:
static code:
txtQ1.Text = ds.Tables("mmsSpecRecord").Rows(0)("Q1")
txtQ2.Text = ds.Tables("mmsSpecRecord").Rows(0)("Q2")
.....
txtQ10.Text = ds.Tables("mmsSpecRecord").Rows(0)("Q10")
where Q1, .. Q10 are field name of a table; and...
|
by: shaikm |
last post by:
Hi,
I have problem passing variable in a FOR LOOP. Following is my code.
Any help much appreciated.
ZS
-- Procedure teta has two parameters l and q , l is the feature table and q is the quality table
create or replace procedure teta(l varchar2,q varchar2)
is
-- a string variable vst is declared to store the SQL statement
| |
by: Bassey |
last post by:
Hi,
This is my code.
create trigger addDnsRecord_staticIphost
on staticIPHost
for insert, update
as
begin
declare @EthMac varchar(255)
|
by: Jim |
last post by:
Hello:
I have an Access database with a table with sequentially numbered
fields (e.g., Q10_1, Q10_2, Q10_3, etc.
What I want to do is cycle through the variables to set them to
values. What I want to do is
___________________________________________
For MaxVariables = 1 To 11 Step 1
|
by: praveena mani |
last post by:
create procedure view_select
(coll int(11))
begin
declare x int;
declare y int;
set x=0;
select count(*) into y from s_details where college_code=coll;
while(x<y) do
select day_number,title,first_name,middle_name,last_name,
date_of_birth,e_mail,ref_number,
|
by: poornimamprabhu |
last post by:
Hi there,
suppose i have piece of code like
main()
{
int i,j;
for(i=0;i<10;i++){
int k = i;
printf("%d %p = *%d\n",i,&k,k);
}
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |