Changing lists inside a list to strings inside a list - python

How do I return my list so that the list is composed of strings rather than lists?
Here is my attempt:
def recipe(listofingredients):
listofingredients = listofingredients
newlist = []
newlist2 = []
for i in listofingredients:
listofingredients = i.strip("\n")
newlist.append(listofingredients)
for i in newlist:
newlist = i.split()
newlist2.append(newlist)
return newlist2
result = recipe(['12345\n','eggs 4\n','$0.50\n','flour 5\n','$2.00\n'])
print result
And my output is this:
[['12345'], ['eggs', '4'], ['$0.50'], ['flour', '5'], ['$2.00']]
Desired output:
['12345', 'eggs', '4', '$0.50', 'flour', '5', '$2.00']
I know that my issue here is appending one list to another, but I'm not sure how to use .strip() and .split() on anything other than a list.

Use extend and split:
>>> L = ['12345\n','eggs 4\n','$0.50\n','flour 5\n','$2.00\n']
>>> res = []
>>> for entry in L:
res.extend(entry.split())
>>> res
['12345', 'eggs', '4', '$0.50', 'flour', '5', '$2.00']
split splits at white spaces per default. Strings with a new line a the end and no space inside are turned into a one-element list:
>>>'12345\n'.split()
['12345']
Strings with a space inside split into a two-element list:
>>> 'eggs 4\n'.split()
['eggs', '4']
The method extend() helps to build a list from other lists:
>>> L = []
>>> L.extend([1, 2, 3])
>>> L
[1, 2, 3]
>>> L.extend([4, 5, 6])
L
[1, 2, 3, 4, 5, 6]

You can use Python's way of doing this. Take the advantage of list comprehension and strip() method.
recipes = ['12345\n','eggs 4\n','$0.50\n','flour 5\n','$2.00\n']
recipes = [recipe.split() for recipe in recipes]
print sum(recipes, [])
Now the result will be
['12345', 'eggs', '4', '$0.50', 'flour', '5', '$2.00']
For further reading
https://stackoverflow.com/a/716482/968442
https://stackoverflow.com/a/716489/968442

Related

List, Convert Str List, replace values, print new str List. Should return ['*', '2', '3', '*', '5']

can any of you help me to identify what am I doing wrong? I know this might be simple but I
am new to programming and Python. I need to return ['*', '2', '3', '*', '5']. Instead of that I am
getting much more values within the list.
Test to replace values in a List
repl_list = [1, 2, 3, 1, 5]
str_repl_list = str(repl_list)
# print('This is the list to replace: ' + str_repl_list)
# print(type(str_repl_list[0]))
new_str_list = []`enter code here`
print(new_str_list)
for item in str_repl_list:
replacement = item.replace('1', '*')
new_str_list.append(replacement)
for index, char in enumerate(new_str_list):
print(index, char) # This is to identify what information is being taken as par of the new list
when you do a str(repl_list), the outpt is a string '[1, 2, 3, 1, 5]', not a list of strings, so if you iterate through str_repl_list you will get
1
,
2
,
3
,
1
,
5
]
Instead you can avoid that step and convert each item to string inside your for loop (str(item))
repl_list = [1, 2, 3, 1, 5]
new_str_list = []
for item in repl_list:
replacement = str(item).replace('1', '*')
new_str_list.append(replacement)
>>> print(new_str_list)
>>> ['*', '2', '3', '*', '5']
you can also use list coprehension
>>> print(['*' if x == 1 else str(x) for x in repl_list])
>>> ['*', '2', '3', '*', '5']
Instead of converting each item to string, you are converting the entire list into a string. Instead try this list comprehension:
str_repl_list = [str(i) for i in str_list]
This will go through each item and convert it into a string, then store it in the new list.
since you are appending each element in the list new_str_list, to see the desired result you need to print them together, so you need to join them in a string and add all element in the string.
so to see the desired result, you just need to add all elment together
which can be done as
str_list_final = ''.join(new_str_list)

Int convert to str using for cycle

why such construction doesn't work?
l = [1,2,3]
for x in l:
x = str(x)
print(l)
it returnes:
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
instead of expected:
['1', '2', '3']
['1', '2', '3']
['1', '2', '3']
For each iteration you're printing the original list without modifying it.
Use map()
list(map(str, l))
>> ['1', '2', '3']
or a list comprehension
l = [str(x) for x in l]
When you do x = str(x) it changes the value in x to str (and not the element in your list l)
But as you are trying to change the list l
I suggest you try a list comprehension:
l = [str(x) for x in l]
You need to store back the casted x back to the list as below:
l = [1,2,3]
new_l = []
for x in l:
new_l.append(str(x))
print(new_l)
Also,if you're not accustomed with map (see other answers) you could use :
for i,x in enumerate(l):
l[i] = str(x)
But other answers are just better.

How to remove specific strings from a list

From the following list how can I remove elements ending with Text.
My expected result is a=['1,2,3,4']
My List is a=['1,2,3,4,5Text,6Text']
Should i use endswith to go about this problem?
Split on commas, then filter on strings that are only digits:
a = [','.join(v for v in a[0].split(',') if v.isdigit())]
Demo:
>>> a=['1,2,3,4,5Text,6Text']
>>> [','.join(v for v in a[0].split(',') if v.isdigit())]
['1,2,3,4']
It looks as if you really wanted to work with lists of more than one element though, at which point you could just filter:
a = ['1', '2', '3', '4', '5Text', '6Text']
a = filter(str.isdigit, a)
or, using a list comprehension (more suitable for Python 3 too):
a = ['1', '2', '3', '4', '5Text', '6Text']
a = [v for v in a if v.isdigit()]
Use str.endswith to filter out such items:
>>> a = ['1,2,3,4,5Text,6Text']
>>> [','.join(x for x in a[0].split(',') if not x.endswith('Text'))]
['1,2,3,4']
Here str.split splits the string at ',' and returns a list:
>>> a[0].split(',')
['1', '2', '3', '4', '5Text', '6Text']
Now filter out items from this list and then join them back using str.join.
try this. This works with every text you have in the end.
a=['1,2,3,4,5Text,6Text']
a = a[0].split(',')
li = []
for v in a:
try : li.append(int(v))
except : pass
print li

How can i sort the list with keys in python

I have the two list dictionary like this
obj1 = [mydict['obj1'],mydict['obj2'],mydict['obj3'],mydict['obj4']]
obj2 = [mydict['obj1'],mydict['obj2'],mydict['obj3'],mydict['obj4'], mydict['obj5'] ]
Now i want that
Count the number of elements in each list
Then based on whichever is greater then get that list of objects
I want a single list which conatins the above two list of(list of) dictionaries based on the higher number of elements so that i cause something like this
mylist = myfunc(objects1, objects2 )
mylist should be a list like [objects1, objects2] depending upon who has greater number of objects.
what is the best way to do that with less lines of code
Something like EDIT
mylist = sorted([obj1, obj2], key=lambda a: len(a), reverse=True)
There's no need to use a lambda function if it's just going to call a function anyway.
>>> objects1 = [1, 2, 3]
>>> objects2 = ['1', '2', '3', '4']
>>>
>>> mylist = [objects1, objects2]
>>> max(mylist, key=len)
['1', '2', '3', '4']
>>> sorted(mylist, key=len, reverse=True)
[['1', '2', '3', '4'], [1, 2, 3]]
objects1 = [1, 2, 3]
objects2 = ['1', '2', '3', '4']
mylist = [objects1, objects2]
mylist.sort(key=len, reverse=True)
print mylist
[['1', '2', '3', '4'], [1, 2, 3]]

Grouping lists within lists in Python 3

I have a list of lists of strings like so:
List1 = [
['John', 'Doe'],
['1','2','3'],
['Henry', 'Doe'],
['4','5','6']
]
That I would like to turn into something like this:
List1 = [
[ ['John', 'Doe'], ['1','2','3'] ],
[ ['Henry', 'Doe'], ['4','5','6'] ]
]
But I seem to be having trouble doing so.
List1 = [['John', 'Doe'], ['1','2','3'],
['Henry', 'Doe'], ['4','5','6'],
['Bob', 'Opoto'], ['10','11','12']]
def pairing(iterable):
it = iter(iterable)
itn = it.next
for x in it :
yield (x,itn())
# The generator pairing(iterable) yields tuples:
for tu in pairing(List1):
print tu
# produces:
(['John', 'Doe'], ['1', '2', '3'])
(['Henry', 'Doe'], ['4', '5', '6'])
(['Bob', 'Opoto'], ['8', '9', '10'])
# If you really want a yielding of lists:
from itertools import imap
# In Python 2. In Python 3, map is a generator
for li in imap(list,pairing(List1)):
print li
# or defining pairing() precisely so:
def pairing(iterable):
it = iter(iterable)
itn = it.next
for x in it :
yield [x,itn()]
# produce
[['John', 'Doe'], ['1', '2', '3']]
[['Henry', 'Doe'], ['4', '5', '6']]
[['Bob', 'Opoto'], ['8', '9', '10']]
Edit: Defining a generator function isn't required, you can do the pairing of a list on the fly:
List1 = [['John', 'Doe'], ['1','2','3'],
['Henry', 'Doe'], ['4','5','6'],
['Bob', 'Opoto'], ['8','9','10']]
it = iter(List1)
itn = it.next
List1 = [ [x,itn()] for x in it]
This should do what you want assuming you always want to take pairs of the inner lists together.
list1 = [['John', 'Doe'], ['1','2','3'], ['Henry', 'Doe'], ['4','5','6']]
output = [list(pair) for pair in zip(list1[::2], list1[1::2])]
It uses zip, which gives you tuples, but if you need it exactly as you've shown, in lists, the outer list comprehension does that.
Here it is in 8 lines. I used tuples rather than lists because it's the "correct" thing to do:
def pairUp(iterable):
"""
[1,2,3,4,5,6] -> [(1,2),(3,4),(5,6)]
"""
sequence = iter(iterable)
for a in sequence:
try:
b = next(sequence)
except StopIteration:
raise Exception('tried to pair-up %s, but has odd number of items' % str(iterable))
yield (a,b)
Demo:
>>> list(pairUp(range(0)))
[]
>>> list(pairUp(range(1)))
Exception: tried to pair-up [0], but has odd number of items
>>> list(pairUp(range(2)))
[(0, 1)]
>>> list(pairUp(range(3)))
Exception: tried to pair-up [0, 1, 2], but has odd number of items
>>> list(pairUp(range(4)))
[(0, 1), (2, 3)]
>>> list(pairUp(range(5)))
Exception: tried to pair-up [0, 1, 2, 3, 4], but has odd number of items
Concise method:
zip(sequence[::2], sequence[1::2])
# does not check for odd number of elements

Categories

Resources