Shortest way to to write split function and assign variables? - python

I'm looking for a shorter but still clean and flexible way to write what I have below.
Variable to work with (length varying)
drpfile_exportname = '1911_CocaCola_XMasNow_TVC30sec_03_Roughcut_Tv10_PV01_Ov01_200319_prev_for_approval_H264'
Long way of doing it but clean
# Split string by "_"
drpfile_exportname_list = drpfile_exportname.split("_")
# Set variables
ul_date = drpfile_exportname_list[0]
up_client = drpfile_exportname_list[1]
up_cprojname = drpfile_exportname_list[2]
# Join variables to create desired name
upload_projname = "_".join((ul_date, up_client, up_cprojname))
Alternative oneliner not so flexible as no variables are assigned and in my opinion not a beautiful way to solve it
upload_projname = ("_".join(drpfile_exportname.split('_')[0:3]))
Thought something like this would work but always had problems with it
ul_date, up_client, up_cprojname = drpfile_exportname.split('_', 2)
Print:
print("\nProject name: {}".format(upload_projname))
Result that should be stored in a variable:
Project name: 1911_CocaCola_XMasNow

You can slice the result of split.
ul_date, up_client, up_cprojname = drpfile_exportname.split('_')[:3]
Or you can assign a dummy variable to the part you want to ignore
ul_date, up_client, up_cprojname, *_ = drpfile_exportname.split('_')

Related

Change part of csv string panda

I would like to change the word consolidation (two times in the following string) with an other value with a variable or ? (ex. breakout/outofconsolidation/inside)
Can I help me to achieve this, please?
dfconsolidationcsv.to_csv(r'symbols\stocks_consolidation_sp500.csv', index = False)
a = ('breakout')
df{a}csv.to_csv(r'symbols\stocks_{a}_sp500.csv', index = False)
Unless there is a justifiable reason to be creating dynamic variable assignments, I would avoid doing so. In this case, defining your DataFrame variables in a dict is probably sufficient:
# store df in a dict instead of separate variables
df_dict = dict()
df_dict['consolidation'] = dfconslidationcv
df_dict['breakout'] = dfbreakoutcv
...
# invoke command for a specific variable
a = 'breakout'
df_dict[a].to_csv(r'symbols\stocks_%s_sp500.csv' % a, index = False)
Now, if there is an overwhelming reason why you HAVE to use pre-existing variable names that need to be changed dynamically, I think you can do something like this:
a = 'breakout'
exec("df%scsv.to_csv(r'symbols\stocks_%s_sp500.csv', index=False)" % (a, a))

Python references to references in python

I have a function that takes given initial conditions for a set of variables and puts the result into another global variable. For example, let's say two of these variables is x and y. Note that x and y must be global variables (because it is too messy/inconvenient to be passing large amounts of references between many functions).
x = 1
y = 2
def myFunction():
global x,y,solution
print(x)
< some code that evaluates using a while loop >
solution = <the result from many iterations of the while loop>
I want to see how the result changes given a change in the initial condition of x and y (and other variables). For flexibility and scalability, I want to do something like this:
varSet = {'genericName0':x, 'genericName1':y} # Dict contains all variables that I wish to alter initial conditions for
R = list(range(10))
for r in R:
varSet['genericName0'] = r #This doesn't work the way I want...
myFunction()
Such that the 'print' line in 'myFunction' outputs the values 0,1,2,...,9 on successive calls.
So basically I'm asking how do you map a key to a value, where the value isn't a standard data type (like an int) but is instead a reference to another value? And having done that, how do you reference that value?
If it's not possible to do it the way I intend: What is the best way to change the value of any given variable by changing the name (of the variable that you wish to set) only?
I'm using Python 3.4, so would prefer a solution that works for Python 3.
EDIT: Fixed up minor syntax problems.
EDIT2: I think maybe a clearer way to ask my question is this:
Consider that you have two dictionaries, one which contains round objects and the other contains fruit. Members of one dictionary can also belong to the other (apples are fruit and round). Now consider that you have the key 'apple' in both dictionaries, and the value refers to the number of apples. When updating the number of apples in one set, you want this number to also transfer to the round objects dictionary, under the key 'apple' without manually updating the dictionary yourself. What's the most pythonic way to handle this?
Instead of making x and y global variables with a separate dictionary to refer to them, make the dictionary directly contain "x" and "y" as keys.
varSet = {'x': 1, 'y': 2}
Then, in your code, whenever you want to refer to these parameters, use varSet['x'] and varSet['y']. When you want to update them use varSet['x'] = newValue and so on. This way the dictionary will always be "up to date" and you don't need to store references to anything.
we are going to take an example of fruits as given in your 2nd edit:
def set_round_val(fruit_dict,round_dict):
fruit_set = set(fruit_dict)
round_set = set(round_dict)
common_set = fruit_set.intersection(round_set) # get common key
for key in common_set:
round_dict[key] = fruit_dict[key] # set modified value in round_dict
return round_dict
fruit_dict = {'apple':34,'orange':30,'mango':20}
round_dict = {'bamboo':10,'apple':34,'orange':20} # values can even be same as fruit_dict
for r in range(1,10):
fruit_set['apple'] = r
round_dict = set_round_val(fruit_dict,round_dict)
print round_dict
Hope this helps.
From what I've gathered from the responses from #BrenBarn and #ebarr, this is the best way to go about the problem (and directly answer EDIT2).
Create a class which encapsulates the common variable:
class Count:
__init__(self,value):
self.value = value
Create the instance of that class:
import Count
no_of_apples = Count.Count(1)
no_of_tennis_balls = Count.Count(5)
no_of_bananas = Count.Count(7)
Create dictionaries with the common variable in both of them:
round = {'tennis_ball':no_of_tennis_balls,'apple':no_of_apples}
fruit = {'banana':no_of_bananas,'apple':no_of_apples}
print(round['apple'].value) #prints 1
fruit['apple'].value = 2
print(round['apple'].value) #prints 2

Python: Convert String to Object Name

This may be a very simple question, but how can I use a string for the name of a class/object declaration? I'm working with PySide, and I have code that will make a text input for every entry in an array.
i=0
d = {}
for name in mtlName:
i = i+1
curOldLabel = d["self.oldLabel" + str(i)]
So now I have to just decalre QtGui.QLineEdit() as what curOldLabel equals (self.oldLabel1 = QtGui.QLineEdit(), self.oldLabel2 = QtGui.QLineEdit(), etc). How do I tell it not to overwrite curOldLabel, but instead use the string as the name for this object?
Your best bet is to use another dictionary to store those objects. It's safe, it's easy to use and it has fast lookup. You don't want to be creating normal variables with dynamic names in most scenarios.

Iteration over variable names in python?

I have a group of variables named k1, k2 k3....k52. They variables are lists/numpy arrays depending on the scenario. Essentially I'd like to perform the same manipulation on them en masse within a loop, but am having trouble ierating over them. Essentially what i'd like is something like this:
for i in arange(0,52):
'k'+ str(i) = log10(eval('k' + str(i)))
Obviously i know the above wont work, but it gives the idea. My actual attempt is this:
for i in arange(0,10):
rate = eval('k' + str(i))
rate = np.array(rate,dtype=float)
rate = log10(rate)
rate.tolist()
vars()[rate] = 'k' + str(i)
(Its changed to a numpy array so i can log it, and then back to a list so i change the variable name back to what it was) Thanks for any help you can provide. I get the feeling this is something quite simple, but its escaping me at the moment.
edit: thanks very much for the answers, i should have explained that I can't really store them a set array, they need to remain as independent variables for reasons i don't really want to go into.
The line:
vars()[rate] = 'k' + str(i)
has to be replaced by:
vars()['k' + str(i)]=rate
If the items are all globals you can use the globals() call to get a mapping, then manipulate them:
g = globals()
for i in arange(0,52):
varname = 'k{}'.format(i)
g[varname] = log10(g[varname])
but you really want to just store all those items in a list or dictionary instead.

Python - efficient way to create 20 variables?

I need to create 20 variables in Python. That variables are all needed, they should initially be empty strings and the empty strings will later be replaced with other strings. I cann not create the variables as needed when they are needed because I also have some if/else statements that need to check whether the variables are still empty or already equal to other strings.
Instead of writing
variable_a = ''
variable_b = ''
....
I thought at something like
list = ['a', 'b']
for item in list:
exec("'variable_'+item+' = '''")
This code does not lead to an error, but still is does not do what I would expect - the variables are not created with the names "variable_1" and so on.
Where is my mistake?
Thanks, Woodpicker
Where is my mistake?
There are possibly three mistakes. The first is that 'variable_' + 'a' obviously isn't equal to 'variable_1'. The second is the quoting in the argument to exec. Do
for x in list:
exec("variable_%s = ''" % x)
to get variable_a etc.
The third mistake is that you're not using a list or dict for this. Just do
variable = dict((x, '') for x in list)
then get the contents of "variable" a with variable['a']. Don't fight the language. Use it.
I have the same question as others (of not using a list or hash), but if you need , you can try this:
for i in xrange(1,20):
locals()['variable_%s' %i] = ''
Im assuming you would just need this in the local scope. Refer to the manual for more information on locals
never used it, but something like this may work:
liste = ['a', 'b']
for item in liste:
locals()[item] = ''

Categories