How could I remove all items in between 2 indexes in a list/tuple?
e.g 'abcdefghijklmnop' with begin = 4 and end = 7 should result in 'abcdhijklmnop' ('efg' removed)
You can use list slicing:
a = [1, 2, 3, 4, 5, 6, 7, 8]
b = a[:3] + a[7:]
print(b)
The result is [1, 2, 3, 8]
Try this:
ip = '123456789'
begin = 3
end = 6
res = ip[:begin]+ip[end:]
output:
123789
You can use list slicing as below:
li = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p']
del li[4:7]
print(li)
output:
['a', 'b', 'c', 'd', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']
As in the post, you've provided it as a string, so in that case you can use string slicing:
s= 'abcdefghijklmnop'
start = 4
end = 7
s= s[0: start:] + s[end::]
print(s)
output:
abcdhijklmnop
Related
for ex.
lst = [2,'j','K','o',6,'x',5,'A',3.2]
I want 3 lists in the form
numbers = [2, 3.2, 5, 6],
uppercase = ['A', 'K'],
lowercase = ['j', 'o', 'x']
I wish to change them into a dictionary of the form
{'numbers': [2, 3.2, 5, 6],
'uppercase': ['A', 'K'],
'lowercase': ['j', 'o', 'x']
how can I achieve this? any help will be appreciated
This is a solution to the problem:
lst = [2,'j','K','o',6,'x',5,'A',3.2]
# get the numbers
numbers = [x for x in lst if type(x)==int or type(x)==float ]
# get the strings
strings = [x for x in lst if type(x)==str]
# get the uppers
upper = [x for x in strings if x.isupper()==True]
# get the lowers
lower = [x for x in strings if x.islower()==True]
# now put into a dict
d = {
'numbers':numbers,
'upper':upper,
'lower':lower
}
# this is the answer as a dict
print(d)
# here there are deperately
print(numbers)
print(upper)
print(lower)
result:
{'numbers': [2, 6, 5, 3.2], 'upper': ['K', 'A'], 'lower': ['j', 'o', 'x']}
And the lists:
[2, 6, 5, 3.2]
['K', 'A']
['j', 'o', 'x']
help me how will I create the getnext function
def getnext(atable, currind):
"""
Given a list of lists, 'atable', and a list of indices one for each row in atable, 'currind',
getnext changes currind in place to make it point to the "next" element in atable.
It returns True if the change was successful, otherwise False.
It also returns False if at least one index points outside atable,
but the last element in currind, that is allowed to be -1 to make it possible
to return pointers to the first element in atable.
Example: atable = [['a', 'b', 'c'], ['d'], ['e', 'f', 'g', 'h'], ['i', 'j']]
currind = [2, 0, 1, 0], points to ['c', 'd', 'f', 'i'].
getnext(atable, currind) returns True and currind becomes:
currind == [2, 0, 1, 1] pointing to ['c', 'd', 'f', 'j'].
If you call again getnext(atable, currind) it returns True and currind becomes:
currind == [2, 0, 2, 0] pointing to ['c', 'd', 'g', 'i'].
If currind were [2, 0, 3, 2], getnext(atable, currind) would return False.
To print the whole atable in order:
currind = [0 for _ in atable]
currind[-1] = -1
while getnext(atable, currind):
print([atable[r][c] for r, c in enumerate(currind)])
"""
I am trying to write a code where it outputs the number of consecutive letters that come after one another as it is running through list_. So all the outputs will start with 1 consecutive number followed by a second and a third if the following value is equivalent. So for example the order ['b','b','b',r] would produce the output of 1,2,3,1 as the consecutive list is disrupt by the upcoming r in the loop so it goes back to 1 consecutive int from 3.
Code for the consecutive bs and rs
list_ = ['b', 'r', 'b', 'r', 'b', 'r', 'b', 'r', 'b', 'b', 'b', 'r', 'b', 'b', 'r', 'r', 'b', 'r', 'r', 'r', 'r', 'r', 'b', 'b', 'b', 'b', 'b', 'r']
for k, gp in groupby(list_):
print(k,list(gp))
This is rle:
What you are looking for is:
from itertools import groupby
rle = lambda x : [k for i,j in groupby(x) for k in range(1,len(list(j)) + 1)]
print(rle(['b','b','b','r']))
[1, 2, 3, 1]
Simple one-liner:
alist = ['b', 'b', 'b', 'r']
print([idx for k, group in itertools.groupby(alist)
for idx, v in enumerate(group, start=1)])
Output:
[1, 2, 3, 1]
I am using the below code currently to split a list into two equal sub lists as below.
Group 1 = [2, 5, 6, 8, 10, 14, 15, 16]
Group 2 = [1, 3, 4, 7, 9, 11, 12, 13]
import random
# Split list into two sub lists
#def sub_lists():
data = list(range(1, 17))
random.shuffle(data)
Group1, Group2 = sorted(data[:8]), sorted(data[8:])
print(Group1, Group2)
# assign randomised values to elements in each group
for i in Group1:
Tasks = ['A', 'B','C']
random.shuffle(Tasks)
with open('Group1_allocation.txt', 'a') as f:
f.write(f'{i} = {Tasks}\n')
for j in Group2:
Tasks = ['A', 'B','C']
random.shuffle(Tasks)
with open('Group2_allocation.txt', 'a') as f:
f.write(f'{j} = {Tasks}\n')
And then assign each element in the sub lists (Group1 and Group 2) three randomised values from a new list (Tasks) such that I get the following output in each fle.
Group1_allocation.txt
2 = ['A', 'B', 'C']
5 = ['B', 'A', 'C']
6 = ['C', 'A', 'B']
8 = ['B', 'A', 'C']
10 = ['C', 'B', 'A']
14 = ['B', 'C', 'A']
15 = ['A', 'C', 'B']
16 = ['C', 'A', 'B']
The script works, but contains repeated code. How could this be coded cleaner/better ?
Here is one way with one less loop:
import random
data = list(range(1, 17))
random.shuffle(data)
l = len(data)
Tasks = ['A', 'B','C']
for i,d in enumerate(data):
filename = 'Group{}_allocation.txt'.format(int(1 + i // (l / 2)))
with open(filename, 'a') as f:
f.write(f'{data[i]} = {Tasks}\n')
I have a double list of this type: dl = [[13, 22, 41], ['c', 'b', 'a']], in which, each element dl[0][i] belongs a value in dl[1][i] (with the same index). How can I sort my list using dl[0] values as my order criteria, maintainning linked both sublists? Sublist are kind of 'linked data', so the previous dl[0][i] and dl[1][i] values must match their index after sorting the parent entire list, using as sorting criteria, the first sublist values
I expect something like:
input: dl = [ [14,22,7,17], ['K', 'M', 'F','A'] ]
output: dl = [ [7, 14, 17, 22], ['F', 'K', 'A', 'M'] ]
This was way too much fun to write. I don't doubt that this function can be greatly improved, but this is what I've gotten in a very short amount of time and should get you started.
I've included some tests just so you can verify that this does indeed do what you want.
from unittest import TestCase, main
def sort_by_first(data):
sorted_data = []
for seq in data:
zipped_to_first = zip(data[0], seq)
sorted_by_first = sorted(zipped_to_first)
unzipped_data = zip(*sorted_by_first)
sorted_data.append(list(tuple(unzipped_data)[1]))
return sorted_data
class SortByFirstTestCase(TestCase):
def test_sort(self):
output_1 = sort_by_first([[1, 3, 5, 2, 4], ['a', 'b', 'c', 'd', 'e']])
self.assertEqual(output_1, [[1, 2, 3, 4, 5], ['a', 'd', 'b', 'e', 'c']])
output_2 = sort_by_first([[9, 1, 5], [21, 22, 23], ['spam', 'foo', 'bar']])
self.assertEqual(output_2, [[1, 5, 9], [22, 23, 21], ['foo', 'bar', 'spam']])
if __name__ == '__main__':
main()
Updated for what you're looking for, selection sort but added another line to switch for the second list to match the first.
for i in range(len(dl[0])):
min_idx = i
for j in range(i+1, len(dl[0])):
if dl[0][min_idx] > dl[0][j]:
min_idx = j
dl[0][i], dl[0][min_idx] = dl[0][min_idx], dl[0][i]
dl[1][i], dl[1][min_idx] = dl[1][min_idx], dl[1][i]
You can try solving this with a for loop also:
dl = [ [3,2,1], ['c', 'b', 'a'] ]
for i in range(0,len(dl)):
dl[i].sort()
print(dl)