I am a total newbie and am doing prep work for the bootcamp. I got stuck with the the following Python exercise:
I have a nested list, say, [[1,2],[3,4]]. The first value in each sub-list is the value to repeat, the second is the amount of times to repeat that value.
I want to get a string with numbers repeated appropriate number of times, like "11, 3333". If there are multiple sets of values, they should be separated by commas; if there is only one set the comma should be omitted. I need to create a function.
I tried to create two separate sub-lists for values and number of repetitions, then np.repeat one list by another.
data_list =[[1,2],[3,4]]
num_list = [val [0] for val in data_list]
repeat_list = [val[1] for val in data_list]
result = np.repeat (num_list, repeat_list)
print (result)
[1 1 3 3 3 3]
In this case I do not know how to separate it with commas. And this is not a function.
I feel like I might need to use np.repeat with "for" loop, but I can not figure out exactly how should it look like.
Thanks.
You could do something like this:
result = ""
for sublist in nested_list:
# For each sublist, turn the first element into a string, and multiply it by the second element, then add a comma
result += str(sublist[0]) * sublist[1] + ","
# Remove the last trailing comma
result = result[:-1]
Without for loop and numpy
', '.join(
map(lambda l: str(l[0])*l[1], data_list)
)
Each entry in list map it to string, then join those strings together
A possible solution :
l= [[1, 2], [3, 4]]
final=[]
for i in l:
final.append(list(str(i[0]) * i[1]))
You could do like this.
data_list =[[1,2],[3,4]]
res = []
for i in data_list:
s = str(i[0]) * i[1]
res.append(s)
print(f'List: {res}')
print(f'String: {", ".join(res)}')
List: ['11', '3333']
String: 11, 3333
Related
How can i replace a string in list of lists in python but i want to apply the changes only to the specific index and not affecting the other index, here some example:
mylist = [["test_one", "test_two"], ["test_one", "test_two"]]
i want to change the word "test" to "my" so the result would be only affecting the second index:
mylist = [["test_one", "my_two"], ["test_one", "my_two"]]
I can figure out how to change both of list but i can't figure out what I'm supposed to do if only change one specific index.
Use indexing:
newlist = []
for l in mylist:
l[1] = l[1].replace("test", "my")
newlist.append(l)
print(newlist)
Or oneliner if you always have two elements in the sublist:
newlist = [[i, j.replace("test", "my")] for i, j in mylist]
print(newlist)
Output:
[['test_one', 'my_two'], ['test_one', 'my_two']]
There is a way to do this on one line but it is not coming to me at the moment. Here is how to do it in two lines.
for two_word_list in mylist:
two_word_list[1] = two_word_list.replace("test", "my")
I want to print all the elements of this list who are directly following "apple".
With
my_list = ["apple","train","apple","bus"]
I would expect the output:
(train,bus)
But my current code
print (my_list[my_list.index("apple") + 1])
only outputs the first one, "train".
How can I get all of them?
If you want to get all items directly following an "apple" in your list, your could use a list comprehension, like:
my_list = ["apple","train","apple","bus", "apple"]
[my_list[i+1] for i, item in enumerate(my_list)
if item == "apple" and i+1 < len(my_list)]
# ['train', 'bus']
We keep the next element whenever the current one is "apple" - and we're not at the end of the list.
my_list = ["apple","train","apple","bus"]
index = my_list.index("apple")
print(my_list[index:index+2])
Have a look at Python's slice syntax. This will print the sublist from index to index + 2 (exclusive).
If you want it as a tuple as you indicated in your question, just wrap it in tuple()
Edit: Of course given that you already have apple you could also just do
print(("apple", my_list[my_list.index("apple") + 1)
I'm new to Python, sorry for the level of this question.
This is my output (prices from a website). I'm wondering how to convert them into a list of ints
for price_list_items in price_list:
for values in price_list_items:
x= values.rstrip(' zł')
print(x)
479 000
355 000
269 000
499 000
289 000
The desired result will like this [479 000,355 000,... ]. Also, I want to be able to perform basic with the values.
I found this thread How to convert a for loop output into a list (python), but it didn't help me.
lista = []
for price_list_items in price_list:
for values in price_list_items:
x= values.rstrip(' zł')
lsita.append(x)
lista = ['479 000', '350 000']
for idx, item in enumerate(lista):
item = item.split()
item = ''.join(item)
lista[idx] = int(item)
print(lista)
~/python/stack$ python3.7 sum.py [479000, 350000]
Change your last line to append to lista instead of print. Now we have lista = ['479 000', ...] but we want ints to perform operations on.
So we can then enumerate our list, from there we can split() and join() to get to here lista = ['479000', ...] then we can just use int(item) and put them back into lista as ints
For fun we could do some map and just go from:
lista = ['479 000', '350 000']
lista = list(map(lambda x: int(''.join((x.split()))), lista))
It looks like your string is meant to be a series of 6-digit numbers but both the individual number-parts, for lack of a better term, are split by spaces and the numbers themselves are split by newlines. The solution, therefore, is to remove the space in between number-parts, converting the result to an integer, like this:
int(part.replace(' ', '')) # Finds all instances of space and replaces them with nothing
Putting this in a list-comprehension, we have:
numbers = [int(l.replace(' ', '')) for l in str]
UPDATE
Since you've posted your code, I can give you a better answer.
[ int(v.rstrip(' zł').replace(' ', '')) for price_list_items in price_list for v in price_list_items ]
What I have is following code snippet:
a = ["2013-11-20,29,0,0", "2013-11-20,3,0,2"]
where a[1] is the a[1]th 5 minute in a day, a[3] and a[4] are number of counts.
I want to sort this by the first two elements. But when I use sort, a[0] always comes first. In fact, I want a[1] to come first. How should I do this?
I have tried to use the key argument in sort(), for example a.sort(key=int). But then an error occurred saying:
ValueError: invalid literal for int() with base 10: '2013-11-20,29,0,0'
Make a key function that returns a tuple of values you want to sort on.
import datetime
a=["2013-11-20,29,0,0","2013-11-20,3,0,2"]
def f(thing):
#separate the values
a,b,c,d = thing.strip().split(',')
# turn one into a datetime.date
y, m, d = map(int, a.split('-'))
a = datetime.date(y, m, d)
# turn the others into ints
b,c,d = map(int, (b,c,d))
# return the values in order of precedence
return (a,b,c,d)
Then use it to sort the list
a.sort(key = f)
Your issue is, that each item in your list is a string. If you sort a string, each character at each position will be compared with eachother. In your example all characters are the same until after the first comma. After the comma, the next characters are a '2' and a '3'. As '3'>'2', the sorting is not as you wish. I assume you want 29 be > 3.
In this particular case, you could just reverse the sorting
a.sort()
a.reverse()
But as you probably have a list with more items, this will not work... The only solution I see is to split each item in your list at the comma ','. Then convert the items which should be considered as integers to int. For example you can do it like this:
a=["2013-11-20,29,0,0","2013-11-20,3,0,2"]
a_temp=[]
for item in a:
splitstr = item.split(',')
i=0
temp = []
for elem in splitstr:
if i>0:
temp_i=int(elem)
else:
temp_i=elem
temp.append(temp_i)
i+=1
a_temp.append(temp)
Your temporary list looks now like this:
[['2013-11-20', 29, 0, 0], ['2013-11-20', 3, 0, 2]]
Then sort it by the position as you wish. This you can do for example like this:
from operator import itemgetter
a_temp_sorted=sorted(a_temp, key=itemgetter(0,1,2,3))
By using the itemgetter you can define in what order you want to sort. Here it is sorted at first by the element 0, then 1, etc... but you can change the order. a_temp_sorted now looks like:
[['2013-11-20', 3, 0, 2], ['2013-11-20', 29, 0, 0]]
Now you can convert your result again to a string. This you can do like this:
a_sorted=[]
for item in a_temp_sorted:
newstring=''
i=0
for elem in item:
if i>0:
temp_i=str(elem)
newstring+=','+temp_i
else:
newstring+=elem
i=1
a_sorted.append(newstring)
a_sorted is now your sorted version of your source a. It now looks like this:
['2013-11-20,3,0,2', '2013-11-20,29,0,0']
I have a list of tuples, its dates and times, from;to
print datetime
gives
[(u'2017-09-10-14-00-35;2017-09-10-14-15-46',), (u'2017-09-10-13-45-23;2017-09-10-14-00-35',), (u'2017-09-10-13-30-05;2017-09-10-13-45-23',)]
I want to make a new list, but only of the 'to' times:
['2017-09-10-14-15-46', '2017-09-10-14-00-35', '2017-09-10-13-45-23']
I cant seem to put all the elements together, so far I have
for a in datetime:
for b in a:
enddates = [b[b.find(";")+1:] for b in a]
print enddates
gives the last result only, not the list
[u'2017-09-10-13-45-23']
Have not given up easily, but down a rabbit hole on this
you don't need any loop, just pick the first & unique item from each tuple, and perform str.partition on it (take 2nd element: the rightmost one), in a list comprehension like you tried
a = [(u'2017-09-10-14-00-35;2017-09-10-14-15-46',), (u'2017-09-10-13-45-23;2017-09-10-14-00-35',), (u'2017-09-10-13-30-05;2017-09-10-13-45-23',)]
enddates = [b[0].partition(";")[2] for b in a]
print(enddates)
result:
['2017-09-10-14-15-46', '2017-09-10-14-00-35', '2017-09-10-13-45-23']
With str.split() function:
dt = [(u'2017-09-10-14-00-35;2017-09-10-14-15-46',), (u'2017-09-10-13-45-23;2017-09-10-14-00-35',), (u'2017-09-10-13-30-05;2017-09-10-13-45-23',)]
result = [d[0].split(';')[1] for d in dt]
print(result)
Or the same with str.rfind() function:
...
result = [d[0][d[0].rfind(';')+1:] for d in dt]
The output:
['2017-09-10-14-15-46', '2017-09-10-14-00-35', '2017-09-10-13-45-23']