I'm trying to separate a string into a list that make sense
for exampia, in order to count the items on the list.
for example: str - "tomatoes,eggs,milk"
and result: lst = ['tomatoes', 'eggs', 'milk']
the code I wrote was:
def separate_groceries(str):
lst = [1, 2, 3] # really limiting the len of str, i need it to be able to recive each str
p = 0
for i in str:
pos = str.find(',')
item = str[:pos]
lst[p] = (item)
p = p + 1
str = str[pos+1:]
return lst
str = "tomatoes,milk,eggs"
res = separate_groceries(str)
print(res)
thank you for your help!
Stimer,
Like Niranjan Nagaraju said, what you may only need is:
groceries_list = "tomatoes,milk,eggs"
res = groceries_list.split(',')
print(res)
You may find more information about the .split() string method in the official Python documentation.
Related
I'm trying to convert an iterator of tuples to an iterator of strings.
I must use itertools, so I'm not allowed to use either for or while.
import itertools
def parlar_lloro(it0):
it1 = filter(lambda x: len(x)>=5, it0)
it2 = map(lambda x: x[:len(x)-2], it1)
it3, it4 = itertools.tee(it2, 2)
n = len(list(it3))
itn = itertools.repeat('CROA', n)
ite = zip(it4, itn)
return itr
What I get when executing this on Python's Shell is:
>>> [(abc,'CROA'),(def,'CROA'),(ghi,'CROA')]
And I want:
>>> ['abc','CROA','def','CROA','ghi','CROA']
If you're suppose to be using itertools then I suspect what you're expected to use is itertools.chain...
Change your return to be (I'm guessing itr is a typo and you meant ite):
return itertools.chain.from_iterable(ite)
Just for reference, the same thing can be accomplished using a list-comp:
res = [sub for el in ((it[:-2], 'CROA') for it in x if len(it) >= 5) for sub in el]
I am new to coding in Python and I am struggling with a very simple problem. There is the same question but for javascript on the forum but it does not help me.
My code is :
def filter_list(l):
for i in l:
if i != str():
l.append(i)
i = i + 1
return(l)
print(filter_list([1,2,'a','b']))
If you can help!
thanks
Before I present solution here are some problems you need to understand.
str()
str() creates a new instance of the string class. Comparing it to an object with == will only be true if that object is the same string.
print(1 == str())
>>> False
print("some str" == str())
>>> False
print('' == str())
>>> True
iterators (no +1)
You have i = i + 1 in your loop. This doesn't make any sense. i comes from for i in l meaning i looping over the members of list l. There's no guarantee you can add 1 to it. On the next loop i will have a new value
l = [1,2,'a']
for i in l:
print(i)
>>> 1
>>> 2
>>> 'a'
To filter you need a new list
You are appending to l when you find a string. This means that when your loop finds an integer it will append it to the end of the list. And later it will find that integer on another loop interation. And append it to the end AGAIN. And find it in the next iteration.... Forever.
Try it out! See the infinite loop for yourself.
def filter_list(l):
for i in l:
print(i)
if type(i) != str:
l.append(i)
return(l)
filter_list([1,2,'a','b'])
Fix 1: Fix the type check
def filter_list(l):
for i in l:
if type(i) != str:
l.append(i)
return(l)
print(filter_list([1,2,'a','b']))
This infinite loops as discussed above
Fix 2: Create a new output array to push to
def filter_list(l):
output = []
for i in l:
if type(i) != str:
output.append(i)
return output
print(filter_list([1,2,'a','b']))
>>> [1,2]
There we go.
Fix 3: Do it in idiomatic python
Let's use a list comprehension
l = [1,2,'a','b']
output = [x for x in l if type(x) != str]
print(output)
>>> [1, 2]
A list comprehension returns the left most expression x for every element in list l provided the expression on the right (type(x) != str) is true.
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)])
For python3, I originally needed to extract odd and even positions from a list and assign it to new lists, then clear the original list. I thought lists were impacted by a function call through "pass by reference". Testing some scenarios, it works sometime. Could someone please explain how exactly python3 works here?
Case 1: empty list is populated with string as expected.
def func1(_in):
_in.append('abc')
mylist = list()
print(f"Before:\nmylist = {mylist}")
func1(mylist)
print(f"After:\nmylist = {mylist}")
Output case 1:
Before:
mylist = []
After:
mylist = ['abc']
Case 2: middle list element is replaced with string as expected.
def func2(_in):
_in[1] = 'abc'
mylist = list(range(3))
print(f"Before:\nmylist = {mylist}")
func2(mylist)
print(f"After:\nmylist = {mylist}")
Output case 2:
Before:
mylist = [0, 1, 2]
After:
mylist = [0, 'abc', 2]
Case 3: why is the list not empty after function call?
def func3(_in):
_in = list()
mylist = list(range(3))
print(f"Before:\nmylist = {mylist}")
func3(mylist)
print(f"After:\nmylist = {mylist}")
Output case 3:
Before:
mylist = [0, 1, 2]
After:
mylist = [0, 1, 2]
Case 4: working exactly as expected, but note I have returned all three lists from function.
def func4_with_ret(_src, _dest1, _dest2):
_dest1 = [val for val in _src[0:len(_src):2]]
_dest2 = [val for val in _src[1:len(_src):2]]
_src = list()
return _src, _dest1, _dest2
source = list(range(6))
evens, odds = list(), list()
print(f"Before function call:\nsource = {source}\nevens = {evens}\nodds = {odds}")
source, evens, odds = func4_with_ret(source, evens, odds)
print(f"\nAfter function call:\nsource = {source}\nevens = {evens}\nodds = {odds}")
Output case 4:
Before function call:
source = [0, 1, 2, 3, 4, 5]
evens = []
odds = []
After function call:
source = []
evens = [0, 2, 4]
odds = [1, 3, 5]
Case 5: why no impact on the variables outside the function if I do not explicitly return from function call?
def func5_no_ret(_src, _dest1, _dest2):
_dest1 = [val for val in _src[0:len(_src):2]]
_dest2 = [val for val in _src[1:len(_src):2]]
_src = list()
source = list(range(6))
evens, odds = list(), list()
print(f"Before function call:\nsource = {source}\nevens = {evens}\nodds = {odds}")
func5_no_ret(source, evens, odds)
print(f"\nAfter function call:\nsource = {source}\nevens = {evens}\nodds = {odds}")
Output case 5:
Before function call:
source = [0, 1, 2, 3, 4, 5]
evens = []
odds = []
After function call:
source = [0, 1, 2, 3, 4, 5]
evens = []
odds = []
Thank you.
Your ultimate problem is confusing (in-place) mutation with rebinding (also referred to somewhat less precisely as "reassignment").
In all the cases where the change isn't visible outside the function, you rebound the name inside the function. When you do:
name = val
it does not matter what used to be in name; it's rebound to val, and the reference to the old object is thrown away. When it's the last reference, this leads to the object being cleaned up; in your case, the argument used to alias an object also bound to a name in the caller, but after rebinding, that aliasing association is lost.
Aside for C/C++ folks: Rebinding is like assigning to a pointer variable, e.g. int *px = pfoo; (initial binding), followed later by px = pbar; (rebinding), where both pfoo and pbar are themselves pointers to int. When the px = pbar; assignment occurs, it doesn't matter that px used to point to the same thing as pfoo, it points to something new now, and following it up with *px = 1; (mutation, not rebinding) only affects whatever pbar points to, leaving the target of pfoo unchanged.
By contrast, mutation doesn't break aliasing associations, so:
name[1] = val
does rebind name[1] itself, but it doesn't rebind name; it continues to refer to the same object as before, it just mutates that object in place, leaving all aliasing intact (so all names aliasing the same object see the result of the change).
For your specific case, you could change the "broken" functions from rebinding to aliasing by changing to slice assignment/deletion or other forms of in-place mutation, e.g.:
def func3(_in):
# _in = list() BAD, rebinds
_in.clear() # Good, method mutates in place
del _in[:] # Good, equivalent to clear
_in[:] = list() # Acceptable; needlessly creates empty list, but closest to original
# code, and has same effect
def func5_no_ret(_src, _dest1, _dest2):
# BAD, all rebinding to new lists, not changing contents of original lists
#_dest1 = [val for val in _src[0:len(_src):2]]
#_dest2 = [val for val in _src[1:len(_src):2]]
#_src = list()
# Acceptable (you should just use multiple return values, not modify caller arguments)
# this isn't C where multiple returns are a PITA
_dest1[:] = _src[::2] # Removed slice components where defaults equivalent
_dest2[:] = _src[1::2] # and dropped pointless listcomp; if _src might not be a list
# list(_src[::2]) is still better than no-op listcomp
_src.clear()
# Best (though clearing _src is still weird)
retval = _src[::2], _src[1::2]
_src.clear()
return retval
# Perhaps overly clever to avoid named temporary:
try:
return _src[::2], _src[1::2]
finally:
_src.clear()
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)