copy variable name with some order in python - python-3.x

like to copy some variable with some calculation.
There is a list and I want to make multiple lists by copy the list.
fruit=['apple','orange']
below lists I want to create from original list
fruit1=['apple1','orange1']
fruit2=['apple2','orange2']
fruit3=['apple3','orange3']
please help

You can try this:
import inspect
fruit = ['apple', 'orange']
def get(v):
for i in reversed(inspect.stack()):
n = [v_name for v_name, v_val in i.frame.f_locals.items() if v_val is v]
if len(n):
return n[0]
for i in range(1, 4):
name_string_order = get(fruit) + str(i)
exec("%s = [fruit[0] + str(i), fruit[1] + str(i)]" % name_string_order)
print(fruit1)
print(fruit2)
print(fruit3)
And out put
['apple1', 'orange1']
['apple2', 'orange2']
['apple3', 'orange3']

Related

python count ocurrences in a tuple of tuples

I have a tuple with tuples inside like this:
tup = ((1,2,3,'Joe'),(3,4,5,'Kevin'),(6,7,8,'Joe'),(10,11,12,'Donald'))
This goes on and on and the numbers don't matter here. The only data that matters are the names. What I need is to count how many times a given name occurs in the tuple and return a list where each item is a list and the number of times it occurs, like this:
list_that_i_want = [['Joe',2],['Kevin',1],['Donald',1]]
I don't want to use any modules or collections like Counter. I want to hard code this.
I actually wanted to hardcode the full solution and not even use the '.count()' method.
So far what I got is this:
def create_list(tuples):
new_list= list()
cont = 0
for tup in tuples:
for name in tup:
name = tup[3]
cont = tup.count(name)
if name not in new_list:
new_list.append(name)
new_list.append(cont)
return new_list
list_that_i_want = create_list(tup)
print(list_that_i_want)
And the output that I am been given is:
['Joe',1,'Kevin',1,'Donald',1]
Any help? Python newbie here.
You could. create a dictionary first and find the counts. Then convert the dictionary to a list of list.
tup = ((1,2,3,'Joe'),(3,4,5,'Kevin'),(6,7,8,'Joe'),(10,11,12,'Donald'))
dx = {}
for _,_,_,nm in tup:
if nm in dx: dx[nm] +=1
else: dx[nm] = 1
list_i_want = [[k,v] for k,v in dx.items()]
print (list_i_want)
You can replace the for_loop and the if statement section to this one line:
for _,_,_,nm in tup: dx[nm] = dx.get(nm, 0) + 1
The output will be
[['Joe', 2], ['Kevin', 1], ['Donald', 1]]
The updated code will be:
tup = ((1,2,3,'Joe'),(3,4,5,'Kevin'),(6,7,8,'Joe'),(10,11,12,'Donald'))
dx = {}
for _,_,_,nm in tup: dx[nm] = dx.get(nm, 0) + 1
list_i_want = [[k,v] for k,v in dx.items()]
print (list_i_want)
Output:
[['Joe', 2], ['Kevin', 1], ['Donald', 1]]
Using an intermediary dict:
def create_list(tuple_of_tuples):
results = {}
for tup in tuple_of_tuples:
name = tup[3]
if name not in results:
results[name] = 0
results[name] += 1
return list(results.items())
Of course, using defaultdict, or even Counter, would be the more Pythonic solution.
You can try with this approach:
tuples = ((1,2,3,'Joe'),(3,4,5,'Kevin'),(6,7,8,'Joe'),(10,11,12,'Donald'))
results = {}
for tup in tuples:
if tup[-1] not in results:
results[tup[-1]] = 1
else:
results[tup[-1]] += 1
new_list = [[key,val] for key,val in results.items()]
Here, a no-counter solution:
results = {}
for t in tup:
results[t[-1]] = results[t[-1]]+1 if (t[-1] in results) else 1
results.items()
#dict_items([('Joe', 2), ('Kevin', 1), ('Donald', 1)])

Need Help Understanding For loops with Variables in Python

I am going through the book Automate the Boring Stuff with Python, and need help understanding what's really happening with the code.
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) + ' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name]
print('The cat names are:')
for name in catNames:
print(' ' + name)
now it makes sense until
for name in catNames:
print(' ' + name)
I am only used to seeing for loops with range(), and this does not make sense to me. A detailed explanation would be highly appreciated thanks
I will explain it to you on a simple example:
# You create some list of elements
list = [1, 2, 3, 9, 4]
# Using for loop you print out all the elements
for i in list:
print(i)
It will print to the console:
1
2
3
9
4
And you can also do it by using range but you have to know the length of the array:
# You create some list of elements
list = [1, 2, 3, 9, 4]
# get the list length
length = len(list)
# Iterating the index
# same as 'for i in range(len(list))'
for i in range(length):
print(list[i])
Console output will look the same as before

Creating tables in a radom in python

My aim is to create a table using two list. I was successful creating this, but I need this result in random order, not in sequence. Here my question how my result to make random from my output.
Is there any other method?
a = [2,3,4,5,6,7,8,9]
b = [12,13,14,15,16,17,19]
for i in b:
for j in a:
print(i,'x',j,'=,')
This should give you the desired result:
from random import randint
a = [2,3,4,5,6,7,8,9]
b = [12,13,14,15,16,17,19]
for i in range(0, len(a)):
for j in range(0, len(b)):
aNum = a[randint(0, len(a)-1)]
bNum = b[randint(0, len(b)-1)]
print(aNum, 'x', bNum, '=')
a.remove(aNum)
b.remove(bNum)

Add filenames to multiple for loops

I have a list of file names, like this.
file_names = ['file1', 'file2']
Also, I have a list of key words I am trying to extract from some files. So, the list of key words (list_1, list_2) and the text string that come from file1 and file2 are below,
## list_1 keywords
list_1 = ['hi', 'hello']
## list_2 keywords
list_2 = ['I', 'am']
## Text strings from file_1 and file_2
big_list = ['hi I am so and so how are you', 'hello hope all goes well by the way I can help you']
My function to extract text,
def my_func(text_string, key_words):
sentences = re.findall(r"([^.]*\.)" ,text_string)
for sentence in sentences:
if all(word in sentence for word in key_words):
return sentence
Now, I am going through multiple lists with two different for loops (as shown below) and with the funciton. After end of each iteration of these multiple for loops, I want to save the file with the filenames from file_names list.
for a,b in zip(list_1,list_2):
for item in big_list:
sentence_1 = my_func(item, a.split(' '))
sentence_2 = my_func(item, b.split(' '))
## Here I would like to add the file name i.e (print(filename))
print(sentence_1)
print(sentence_2)
I need an output that looks like this,
file1 is:
None
file2 is:
None
You can ignore None in my output now, as my main focus is to iterate though filename list and add them to my output. I would appreciate any help to achieve this.
You can access the index in Python for loops and use this index to find the file to which the string corresponds. With this you can print out the current file.
Here is an example of how you can do it:
for a,b in zip(list_1,list_2):
# idx is the index here
for idx, item in enumerate(big_list):
sentence_1 = extract_text(item, a)
sentence_2 = extract_text(item, b)
prefix = file_names[idx] + " is: " # Use idx to get the file from the file list
if sentence_1 is not None:
print(prefix + sentence_1)
if sentence_2 is not None:
print(prefix + sentence_2)
Update:
If you want to print the results after the iteration you can save temporarily the results in a dictionary and then loop through it:
for a,b in zip(list_1,list_2):
# idx is the index here
resMap = {}
for idx, item in enumerate(big_list):
sentence_1 = extract_text(item, a)
sentence_2 = extract_text(item, b)
if sentence_1 is not None:
resMap[file_names[idx]] = sentence_1
if sentence_2 is not None:
resMap[file_names[idx]] = sentence_2
for k in resMap.keys():
prefix = k + " is: " # Use idx to get the file from the file list
print (prefix + resMap[k])

No shortcut : save dict to file / count items in dict

Python 3
Hello guys I'm a python beginner studying dictionary now
below is what I have learned so far how to save list into a file
and count items in list like below.
class item:
name = None
score = None
def save_list_in_file(file_name:str, L:[item]):
f = open(file_name,'w')
for it in L:
f.write(it.name + "" + str(it.score))
f.close()
def count_item_in_list(L:[item])->int:
n = 0
for it in L:
if it.score >= 72:
n += 1
return n
and I'm not sure if using dictionary is same way as I use in list
for example:
def save_dict_to_file(file_name:str, D:{item}):
f = open(file_name,'w')
for it in D:
f.write(it.name + "" + str(it.score))
f.close()
def count_item_in_dict(D:{item})->int:
n = 0
for it in D:
if it.score <= 72:
n += 1
return n
will be correct? i thought dict would be different than using a list.
Thanks for any comment!
You can't use a dictionary the same way as using a list.
A list is defined as a sequence of elements. So when you have the list:
L=['D','a','v','i','d']
You can loop it like this:
for it in L:
print(it)
And it will print:
D
a
v
i
d
Instead, a dictionary is a group of tuples of two elements where one is the key and the second is the value. So for example you have a Dictonary like this:
D = {'firstletter' : 'D', 'secondletter': 'a', 'thirdletter' : 'v' }
And when you loop it like a list:
for it in L:
print(it)
it will print only the keys:
firstletter
secondletter
thirdletter
so in order to obtain the values you have to print it like this:
for it in D:
print(D[it])
that will display this result:
D
a
v
If you need more information you can check de documentation for dictionary :)
Python 3 documentation of Data Structures

Resources