How to use data from one function in another function? - python

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

Related

How do you convert the quotient of a division of two polynomials to a standard polynomial instead of a tuple in Python [duplicate]

I would like to know if there is a better way to print all objects in a Python list than this :
myList = [Person("Foo"), Person("Bar")]
print("\n".join(map(str, myList)))
Foo
Bar
I read this way is not really good :
myList = [Person("Foo"), Person("Bar")]
for p in myList:
print(p)
Isn't there something like :
print(p) for p in myList
If not, my question is... why ? If we can do this kind of stuff with comprehensive lists, why not as a simple statement outside a list ?
Assuming you are using Python 3.x:
print(*myList, sep='\n')
You can get the same behavior on Python 2.x using from __future__ import print_function, as noted by mgilson in comments.
With the print statement on Python 2.x you will need iteration of some kind, regarding your question about print(p) for p in myList not working, you can just use the following which does the same thing and is still one line:
for p in myList: print p
For a solution that uses '\n'.join(), I prefer list comprehensions and generators over map() so I would probably use the following:
print '\n'.join(str(p) for p in myList)
I use this all the time :
#!/usr/bin/python
l = [1,2,3,7]
print "".join([str(x) for x in l])
[print(a) for a in list] will give a bunch of None types at the end though it prints out all the items
For Python 2.*:
If you overload the function __str__() for your Person class, you can omit the part with map(str, ...). Another way for this is creating a function, just like you wrote:
def write_list(lst):
for item in lst:
print str(item)
...
write_list(MyList)
There is in Python 3.* the argument sep for the print() function. Take a look at documentation.
Expanding #lucasg's answer (inspired by the comment it received):
To get a formatted list output, you can do something along these lines:
l = [1,2,5]
print ", ".join('%02d'%x for x in l)
01, 02, 05
Now the ", " provides the separator (only between items, not at the end) and the formatting string '02d'combined with %x gives a formatted string for each item x - in this case, formatted as an integer with two digits, left-filled with zeros.
To display each content, I use:
mylist = ['foo', 'bar']
indexval = 0
for i in range(len(mylist)):
print(mylist[indexval])
indexval += 1
Example of using in a function:
def showAll(listname, startat):
indexval = startat
try:
for i in range(len(mylist)):
print(mylist[indexval])
indexval = indexval + 1
except IndexError:
print('That index value you gave is out of range.')
Hope I helped.
I think this is the most convenient if you just want to see the content in the list:
myList = ['foo', 'bar']
print('myList is %s' % str(myList))
Simple, easy to read and can be used together with format string.
I recently made a password generator and although I'm VERY NEW to python, I whipped this up as a way to display all items in a list (with small edits to fit your needs...
x = 0
up = 0
passwordText = ""
password = []
userInput = int(input("Enter how many characters you want your password to be: "))
print("\n\n\n") # spacing
while x <= (userInput - 1): #loops as many times as the user inputs above
password.extend([choice(groups.characters)]) #adds random character from groups file that has all lower/uppercase letters and all numbers
x = x+1 #adds 1 to x w/o using x ++1 as I get many errors w/ that
passwordText = passwordText + password[up]
up = up+1 # same as x increase
print(passwordText)
Like I said, IM VERY NEW to Python and I'm sure this is way to clunky for a expert, but I'm just here for another example
Assuming you are fine with your list being printed [1,2,3], then an easy way in Python3 is:
mylist=[1,2,3,'lorem','ipsum','dolor','sit','amet']
print(f"There are {len(mylist):d} items in this lorem list: {str(mylist):s}")
Running this produces the following output:
There are 8 items in this lorem list: [1, 2, 3, 'lorem', 'ipsum',
'dolor', 'sit', 'amet']
OP's question is: does something like following exists, if not then why
print(p) for p in myList # doesn't work, OP's intuition
answer is, it does exist which is:
[p for p in myList] #works perfectly
Basically, use [] for list comprehension and get rid of print to avoiding printing None. To see why print prints None see this
To print each element of a given list using a single line code
for i in result: print(i)
You can also make use of the len() function and identify the length of the list to print the elements as shown in the below example:
sample_list = ['Python', 'is', 'Easy']
for i in range(0, len(sample_list)):
print(sample_list[i])
Reference : https://favtutor.com/blogs/print-list-python
you can try doing this: this will also print it as a string
print(''.join([p for p in myList]))
or if you want to a make it print a newline every time it prints something
print(''.join([p+'\n' for p in myList]))

Trying to write a program that checks the number of characters in each string in a list

def friend(x):
new_name_list = []
for each_name in x:
name_count = 0
for each_char in each_name:
name_count += 1
if name_count == 4:
new_name_list.append(each_name)
print(new_name_list)
I'm trying to complete a codewars problem which is as follows: "Make a program that filters a list of strings and returns a list with only your friends name in it.
The name has to have exactly 4 letters in it.
Ex: Input = ["Ryan", "Kieran", "Jason", "Yous"], Output = ["Ryan", "Yous"]"
I've created the program above which seems to run fine in PyCharm and work for each list I test it with. However when I check it with codewars it keeps giving me an error message. Not too sure what I'm doing wrong any help would be appreciated.
could also just use a basic list comprehension:
[name for name in Input if len(name)==4]
or even use compress from itertools:
from itertools import compress
mask = [len(name)==4 for name in Input]
list(compress(Input,mask))
output:
['Ryan', 'Yous']
You can use:
def friend(x):
print(list(filter(lambda name: len(name)==4, x)))
or
def friend(x):
names_to_print = []
for name in x:
if len(name) == 4:
names_to_print.append(name)
print(names_to_print)
If you want to return only, just replace print statement with return.
Learning python and trying to solve the same problem. I wrote the code below and would like to find out how to move-on following "my logic" way.
It seems that it adds just the very first item to the new_friends list and not iterating over all the elements of x list.
Beside above, the return value is giving back > None ... what is the thing I'm not noticing here?
def friend(x):
x = ["Ryan", "Kieran", "Jason", "Yous"]
new_friends = []
for str in x:
if len(str) == 4:
return new_friends.append(str)
return new_friends[0:]
Instead of if statement I also tried a nested while loop .. but no success adding other items to the new_friends list.
Thank you so much for your answers ;)

Python access elements of a list of strings [duplicate]

I would like to know if there is a better way to print all objects in a Python list than this :
myList = [Person("Foo"), Person("Bar")]
print("\n".join(map(str, myList)))
Foo
Bar
I read this way is not really good :
myList = [Person("Foo"), Person("Bar")]
for p in myList:
print(p)
Isn't there something like :
print(p) for p in myList
If not, my question is... why ? If we can do this kind of stuff with comprehensive lists, why not as a simple statement outside a list ?
Assuming you are using Python 3.x:
print(*myList, sep='\n')
You can get the same behavior on Python 2.x using from __future__ import print_function, as noted by mgilson in comments.
With the print statement on Python 2.x you will need iteration of some kind, regarding your question about print(p) for p in myList not working, you can just use the following which does the same thing and is still one line:
for p in myList: print p
For a solution that uses '\n'.join(), I prefer list comprehensions and generators over map() so I would probably use the following:
print '\n'.join(str(p) for p in myList)
I use this all the time :
#!/usr/bin/python
l = [1,2,3,7]
print "".join([str(x) for x in l])
[print(a) for a in list] will give a bunch of None types at the end though it prints out all the items
For Python 2.*:
If you overload the function __str__() for your Person class, you can omit the part with map(str, ...). Another way for this is creating a function, just like you wrote:
def write_list(lst):
for item in lst:
print str(item)
...
write_list(MyList)
There is in Python 3.* the argument sep for the print() function. Take a look at documentation.
Expanding #lucasg's answer (inspired by the comment it received):
To get a formatted list output, you can do something along these lines:
l = [1,2,5]
print ", ".join('%02d'%x for x in l)
01, 02, 05
Now the ", " provides the separator (only between items, not at the end) and the formatting string '02d'combined with %x gives a formatted string for each item x - in this case, formatted as an integer with two digits, left-filled with zeros.
To display each content, I use:
mylist = ['foo', 'bar']
indexval = 0
for i in range(len(mylist)):
print(mylist[indexval])
indexval += 1
Example of using in a function:
def showAll(listname, startat):
indexval = startat
try:
for i in range(len(mylist)):
print(mylist[indexval])
indexval = indexval + 1
except IndexError:
print('That index value you gave is out of range.')
Hope I helped.
I think this is the most convenient if you just want to see the content in the list:
myList = ['foo', 'bar']
print('myList is %s' % str(myList))
Simple, easy to read and can be used together with format string.
I recently made a password generator and although I'm VERY NEW to python, I whipped this up as a way to display all items in a list (with small edits to fit your needs...
x = 0
up = 0
passwordText = ""
password = []
userInput = int(input("Enter how many characters you want your password to be: "))
print("\n\n\n") # spacing
while x <= (userInput - 1): #loops as many times as the user inputs above
password.extend([choice(groups.characters)]) #adds random character from groups file that has all lower/uppercase letters and all numbers
x = x+1 #adds 1 to x w/o using x ++1 as I get many errors w/ that
passwordText = passwordText + password[up]
up = up+1 # same as x increase
print(passwordText)
Like I said, IM VERY NEW to Python and I'm sure this is way to clunky for a expert, but I'm just here for another example
Assuming you are fine with your list being printed [1,2,3], then an easy way in Python3 is:
mylist=[1,2,3,'lorem','ipsum','dolor','sit','amet']
print(f"There are {len(mylist):d} items in this lorem list: {str(mylist):s}")
Running this produces the following output:
There are 8 items in this lorem list: [1, 2, 3, 'lorem', 'ipsum',
'dolor', 'sit', 'amet']
OP's question is: does something like following exists, if not then why
print(p) for p in myList # doesn't work, OP's intuition
answer is, it does exist which is:
[p for p in myList] #works perfectly
Basically, use [] for list comprehension and get rid of print to avoiding printing None. To see why print prints None see this
To print each element of a given list using a single line code
for i in result: print(i)
You can also make use of the len() function and identify the length of the list to print the elements as shown in the below example:
sample_list = ['Python', 'is', 'Easy']
for i in range(0, len(sample_list)):
print(sample_list[i])
Reference : https://favtutor.com/blogs/print-list-python
you can try doing this: this will also print it as a string
print(''.join([p for p in myList]))
or if you want to a make it print a newline every time it prints something
print(''.join([p+'\n' for p in myList]))

How to append values to a python dictionary and return it in a function call

I have a for loop within a python function call that executes a number of times. I need to return the values in a dictionary to dump them into a db.
Here is a piece of sample code, how can I append values to a dictionary and ensure I have all of them for further use.
def parser_code():
log = dict()
for i in range(len):
log['abc'] = 2*i
log['xyz'] = 10+i
return log
This will execute atleast twice so I want a dictionary to be log = {['abc':2, 'xyz':11],['abc':3, 'xyz':12]}
How can I append to the result each time? Or is there a smarter way to do this?
I'm not 100% sure what behavior you're expecting, but I think this code should suffice:
def parser_code(length):
log = list()
for i in range(length):
this_dict = dict()
this_dict['abc'] = 2*i
this_dict['xyz'] = 10+i
log.append(this_dict)
return log
I think you are looking for defaultdict part of std-libs.
from collections import defaultdict
glog = defaultdict(list)
def parser_code(dd):
for i in range(length):
dd['abc'].append(2*i)
return dd
glog = parser_code(glog)
if you actually want to use your result you have to have make sure that the dict is not created new for every call to your function.
still a bit unclear if you need a dict or not, you will only need that if you want the ability for key-lookup. If you are happy with just making a list (array) of numbers, then go ahead and use a list.
glog = list()
def parser_code(lst):
return lst + [2*i for i in range(length)]
glog = parser_code(glog)
you can give the dictionary as a parameter to your function.
please not that your code is not working for me (original indention of the for loop - it's corrected now) and the len parameter). I needed to guess a little bit what you are actually doing. Could you take a look at your example code in the question or comment here?
def parser_code(result, length):
for i in range(length):
result['abc'] = 2*i
result['xyz'] = 10+i
return result
d = {}
parser_code(d, 3)
print(d)
parser_code(d, 3)
print(d)
will give this output:
python3 ./main.py
{'abc': 4, 'xyz': 12}
{'abc': 4, 'xyz': 12}

Searching for a character or string of characters in a list (like the find function on websites)

My first post here.
I'd like to create a search function, searching a list for any raw_input entered.
So far, I've been able to call a path on computer and append each item to a list.
I know I can list.index() for a complete file name, but I'd like it to search for
simply any character(s) one might want to input.
Here's what I've got so far:::
import os
list1 = []
x = "/Users/User/temp"
vec = os.listdir(x)
for p in vec:
list1.append(p)
for line in list1:
print line
o = raw_input("search>>> ")
print list.index(o)
Now, with this code, the filename has to be typed in exactly...
So, it'll take my path(users/user/temp) and make a list from it, search
the list for the filename and return the index at which it lies.
How can I search for say.. (you) in the list and bring up a result that
might be (youarewonderful.txt).
Thanks, I'm very new to Python, so any insight or code improvements are welcome
as well.
-peer
This gives a list of indices:
[i for i, x in enumerate(vec) if "you" in x]
This is called a list comprehension, and it uses the enumerate function to keep track of the indices. If you aren't familiar with these, I recommend the official python tutorial here
I've got a lead!
Next, I added:::
for p in vec:
if 'yo' in p:
print p
print list1.index(p)
Sorry Patrick, this is more along the lines of what I wanted to do. Thanks anyways! -although I don't quite get what you were getting at. I'd like to know, though.
Here is completed program, don't know how I got here:::
import os
list1 = []
x = "/Users/User/temp"
vec = os.listdir(x)
for p in vec:
list1.append(p)
for line in list1:
print line
b = raw_input('search for item in list/path>>> ')
for p in vec:
if str(b) in p:
print p
print list1.index(p)
Woo Hoo
-peer

Categories

Resources