What are the possible ways of reversing order of any output?
For example, if I have a code like this:
for i in range(10):
print(i)
This is fairly a simple example of course. I can just say
for i in range(9, -1, -1):
print(i)
But what happens when you have very complicated functions, lists, maps, arrays, etc. So my question is: Is there a generic way (or ways) to reverse the order of any output?
I've been thinking about pushing every element (element can be anything) onto a stack, then pop() elements and printing the popped element. But maybe there are better solutions
You can use the reversed builtin:
for i in reversed(range(10)):
print(i)
output:
9
8
7
6
5
4
3
2
1
0
for i in range(10)[::-1]:
print(i)
OUTPUT
9
8
7
6
5
4
3
2
1
0
Related
consider a list l=[1,2,3,4,5].
if we want to unpack the list and also to print, we use * operator to unpack
l=[1,2,3,4,5]
print(*l,sep="\n")
output:
1
2
3
4
5
It is in case of single simple list.
If I have nested list and want to unpack all the sublists like aboveā.
consider a sublist sl=[[1,2,3],[4,5,6],[7,8,9]]
If I put ** in the print satement it throws an error message.
sl=[[1,2,3],[4,5,6],[7,8,9]]
print(**sl,sep="\n")
It doesn't work.
I want the output as
1
2
3
4
5
6
7
8
9
Is there any chance to unpack the sublists of nested list without loops
You can use itertools.chain like below:
>>> from itertools import chain
>>> sl=[[1,2,3],[4,5,6],[7,8,9]]
>>> print(*(chain.from_iterable(sl)),sep="\n")
1
2
3
4
5
6
7
8
9
You could flatten the list and then unpack it.
l = [[1,2,3],[4,5,6],[7,8,9]]
print(*[elt for sl in l for elt in sl])
To get the output you require you could do this:
sl=[[1,2,3],[4,5,6],[7,8,9]]
print('\n'.join([str(x) for y in sl for x in y]))
This question already has answers here:
Accessing the index in 'for' loops
(26 answers)
Closed 1 year ago.
Here I have a list:
some_list = [a','r','p','i','l','a','z','a','r','l','i','i','l','z','p']
I want some function to index each of the characters in the list with an unique index.
So the code should be something like:
for char in some_list:
char_index = some_list.magic_index(char)
print(char_index)
magic_index should be a function that returns a number from 0 to 14 incrementally for each character.
The output should be something like:
0
1
2
3
4
4
5
6
7
8
9
10
11
12
13
14
I know this isn't really indexing each character, but I just want some function to return a value from 0 to 14 for each character, so that each character has their own unique number from 0 to 14.
I know this is kind of a dumb question, it is some how just very hard for me. If someone know how to solve this, please give me some help. Thank you!
Use enumerate and build a map of characters to indices:
>>> magic_index = {c: i for i, c in enumerate(some_list)}.get
>>> magic_index('a')
7
This question already has answers here:
How do I pass a variable by reference?
(39 answers)
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 1 year ago.
I'm trying to make a shuffled copy of an array called tst. I've defined a copy of tst called batch, and then shuffled batch so that tst remains intact & unshuffled. However, in doing so, I'm finding that shuffling batch also (for some reason) shuffles tst in the process.
To fully understand my dilemma, consider the following code snippet:
# First code snippet
tst = np.array([0,1,2,3,4,5,6,7,8,9])
batch = tst
print(tst)
print(batch)
seed = 42
np.random.seed(seed)
np.random.shuffle(batch)
print(tst)
print(batch)
When I run my code, the outputs that correspond to this code snippet look like this:
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[8 1 5 0 7 2 9 4 3 6]
[8 1 5 0 7 2 9 4 3 6]
...whereas I'd think it would look like this:
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]
[8 1 5 0 7 2 9 4 3 6]
Loosely speaking, my first thought was that tst and batch are "looking" at the same location in memory (I'm not experienced in programming, so I apologize if my terminology is wrong), and so updating the particular value in that location might update any other variables "looking" at the same place. However, if this was the case, then I would assume that running the following code:
# Second code snippet
a = 5
b = a
print(a)
print(b)
a = 3
print(a)
print(b)
...would output:
5
5
3
3
However, this is not the case...Instead, it outputs:
5
5
3
5
Truth be told, the output behavior of the second code snippet is what I initially thought would happen with the first code snippet, as this seems to make much more sense to me. Performing an operation on one variable shouldn't affect any other "equal" variables, unless explicitly specified by some supplemental code or something.
Alas, I'm hoping to understand why the outputs of the first code snippet behave differently than the outputs of the second code snippet, and what needs to change so that I can shuffle batch without also shuffling tst at the same time. I've been looking around online for an answer, but I feel like everything I find is either too advanced for my current skillset, and/or simply doesn't pertain to this exact issue. Any help would be appreciated. Thanks in advance!
You have to use ndarray.copy, or other similar method, if you really want to create array copy. a = b just creates another variable that points to the same array. Variables are just references to "real piece of data" in python and many other languages. Sometimes a = b is a save way to create a backup for 'immutable data' such as scalars or tuples, but with mutable data types, which can be changed 'in place', that is mutated, this usually fails. Take extra care with arrays, lists, objects, dictionaries and any other "mutable" data types.
https://numpy.org/doc/stable/reference/generated/numpy.ndarray.copy.html#numpy.ndarray.copy
I am stuck in a program where I have to print "Block" before every 5 numbers without using an additional variable.
This is the code:
for index,i in enumerate(range(1,11)):
print(i)
expected output:
Block
1
2
3
4
5
Block
6
7
8
9
10
Please help new to python.
The expression x % 5 will give you zero if and only if x is a multiple of five.
So, if you wanted to output "Block" before 1, 6, 11, ..., you could use:
if (i - 1) % 5 == 0: print('Block')
before printing the number.
In other words, it's as simple as:
for i in range(1, 11):
if (i - 1) % 5 == 0: print('Block')
print(i)
Running that program gives your expected output of:
Block
1
2
3
4
5
Block
6
7
8
9
10
Note that this will only work if you start at one (as it appears you do). Any other start point will require a slightly modified solution.
In python this can be done by
For index,I in enumerate (range(1,21)):
Print(i)
if(i%5==0):
Print("block")
I am writing a test that needs to plug in values from a list to a peripheral going forwards then backwards sequentially without breaking the loop. here is the structure I need to modify:
exampleList = [5 10 60 9 3]
for i, listValue in enumerate(exampleList):
self.log += 'Status: iteration {0}, sending {1}\n'.format(i, listValue)
self.device.writeToPeripheral(listValue)
...
I am trying to essentially write [5 10 60 9 3 3 9 60 10 5] (single or extra middle value doesn't matter) to an external device. Changing the list contents will mess up critical objects elsewhere in the environment for different tests. Is there a creative way in python to structure the loop to iterate going up the list, then back down immediately after? I could simply put this in a function and reverse the list after the first call, but I would like to avoid this approach if possible.
One way is to use itertools.chain() like:
Code:
import itertools as it
exampleList = [5, 10, 60, 9, 3]
forward_back = it.chain(exampleList, reversed(exampleList))
for i, list_value in enumerate(forward_back):
print i, list_value
Results:
0 5
1 10
2 60
3 9
4 3
5 3
6 9
7 60
8 10
9 5
Another option is to append the reversed list when iterating:
for i, list_value in enumerate(exampleList + exampleList[::-1]):