print an array vertically - python

I recently found out how to print an array vertically but I have yet to find out how to choose when to increment it
array = ['1', '2', '3', '5', '7', '11', '13',]
array = map(str,array)
array = list(array)
print("\n".join(array))
output example:
1
2
3
5
7
11
13
output goal:
1, 2, 3, 5, 7,
11, 13,

array = ['1', '2', '3', '5', '7', '11', '13',]
for i in range(len(array)):
print(array[i], end=', ')
if i % 5 == 4:
print()

To perform the desired print out of the provided array, this will work (with the addition of a newline in between):
array = ['1', '2', '3', '5', '7', '11', '13']
for n in array[:-2]:
print(n + ',', end=' ')
print('\n')
for n in array[-2:]:
print(n + ',', end=' ')
Returns:
1, 2, 3, 5, 7,
11, 13,

Related

Python insert list items into every 3rd slot of larger list

So I have two lists in python,
letters = ['1', '2', '4', '5', '7', '8']
list = ['3', '6', '9']
and I would like to merge these two lists into one.
That looks like so:
['1', '2', '3', '4', '5', '6', '7', '8', '9']
Here is the code I am running
letters = ['1','2','4','5','7','8']
list = ['3','6','9']
new_list = []
n = 2
length = len(list)
i = 0
while i < length:
for start_index in range(0, len(letters), n):
new_list.extend(letters[start_index:start_index+n])
print(list[i])
new_list.append(list[i])
i += 1
new_list.pop()
print(new_list)
which results in:
['1', '2', '3', '4', '5', '6', '7', '8']
whilst I am expecting
['1', '2', '3', '4', '5', '6', '7', '8', '9']
also the order is not alpha-numeric, the goal is to iterate through the smaller list and place each item into every 3rd slot of the larger list.
Assuming that the numbers given are just placeholders, and not meant to actually be sorted:
One way to interleave items would be using iterators manually:
letters = ['1','2','4','5','7','8']
lst = ['3','6','9']
a = iter(letters)
b = iter(lst)
new_list = []
try:
while True:
if len(new_list) % 3 == 2:
new_list.append(next(b))
else:
new_list.append(next(a))
except StopIteration:
pass
Or for an entirely different, more terse, solution, you could use itertools.chain alongside zip():
import itertools
letters = ['1','2','4','5','7','8']
lst = ['3','6','9']
new_list = list(itertools.chain(*zip(letters[::2], letters[1::2], lst)))
# letters[::2] -> 1, 4, 7
# letters[1::2] -> 2, 5, 8
# lst -> 3, 6, 9
#
# zip(...) -> (1, 2, 3), (4, 5, 6), (7, 8, 9)
# chain(...) -> 1, 2, 3, 4, 5, 6, 7, 8, 9
I have edited your own code and used for loop instead of while:
letters = ['1','2','4','5','7','8']
myList = ['3','6','9']
new_list = []
length = len(myList) + len(letters)
j = 0
for i in range(1,length+1):
if i % 3 == 0:
new_list.append(myList[i//3 - 1])
j -= 1
else:
new_list.append(letters[i + j - 1])
print(new_list)
Output
['1', '2', '3', '4', '5', '6', '7', '8', '9']
Let's have another example:
letters = ['a','b','c','d','e','f']
myList = ['1','2','3']
new_list = []
length = len(myList) + len(letters)
j = 0
for i in range(1,length+1):
if i % 3 == 0:
new_list.append(myList[i//3 - 1])
j -= 1
else:
new_list.append(letters[i + j - 1])
print(new_list)
Output
['a', 'b', '1', 'c', 'd', '2', 'e', 'f', '3']
Note that this only works when the number of elements in the myList variable will be multiple of 3.
In Python 3.10, you can use itertools.pairwise:
import itertools
letters = ['1','2','4','5','7','8']
new = ['3', '6', '9']
result = []
for pair, single in zip(itertools.pairwise(letters), new):
result.extend(pair)
result.append(single)
Or more generally (and for a pairwise replacement for before 3.10):
def by_n(iterable, n):
return zip(*[iter(iterable)]*n)
result = []
for triple, single in zip(by_n(letters, 3), new):
result.extend(triple)
result.append(single)

How to remove ' ' from my list python 3.2

newlist=['21', '6', '13', '6', '11', '5', '6', '10', '11', '11', '21', '17', '23', '10', '36', '4', '4', '7', '23', '6', '12', '2', '7', '5', '14', '3', '10', '5', '9', '43', '38']
Now what I want to do with this list is take out the ' ' surrounding each integer, the problem is that the split() function or the strip() function wont work. So I don't know how to remove it. Help.
AttributeError: 'list' object has no attribute 'split' is given when I run.
Also After that I want to find the sum of each 7 integers in the list, and that I also don't know where to start. Any help would be appreciated.
That doesn't work because it is a list of strings rather than integers.
x = [int(x) for x in newlist]
This will cast every value in the list to be an int.
Also After that I want to find the sum of each 7 integers in the list
^ Can you clarify what this means? Is this the sum of every seven consecutive numbers until the end of the list? If so,
sums = []
index = 0
for i in range(0, len(newlist), 7):
sums[index] = sum(newlist[i : i + 7)])
index += 1
EDIT:
Full code:
x = [int(x) for x in newlist]
sums = []
for i in range(0, len(x), 7):
sums.append(sum(x[i : i + 7]))
What you have is a list of strings (hence the ''s), and you want to convert them to integers. The boring solution to the problem is a simple for loop:
for i in range(len(newlist)):
newlist[i] = int(newlist[i]
The more compact method is a list comprehension, which you can read about here: List Comprehensions:
newlist = [int(num) for num in newlist]
The two functions you mentioned operate only on single strings.
>>> "Hi my name is Bob".split(" ")
["Hi", "my", "name", "is", "Bob"]
>>> "GARBAGE This string is surrounded by GARBAGE".strip("GARBAGE")
" This string is surrounded by "
As #Tomoko Sakurayama mentioned, you can sum simply enough with another loop. If you're feeling fancy, though, you can use another list comprehension (or even stack it on the old one, though that's not very Pythonic :).
[sum(newlist[i:i+7]) for i in range(0, len(newlist) - 6, 7)] + [sum(newlist[-(len(newlist) % 7):])]
You are probably looking for python's map function:
oldlist = ['21', '6', '13', '6', '11', '5', '6', '10', '11', '11', '21', '17', '23', '10', '36', '4', '4', '7', '23', '6', '12', '2', '7', '5', '14', '3', '10', '5', '9', '43', '38']
newlist = list(map(int, oldlist))
print(type(newlist[0]))
print(newlist)
And output:
<class 'int'>
[21, 6, 13, 6, 11, 5, 6, 10, 11, 11, 21, 17, 23, 10, 36, 4, 4, 7, 23, 6, 12, 2, 7, 5, 14, 3, 10, 5, 9, 43, 38]
You can use map for this case;
new_list = list(map(int, newlist))
print(new_list) == [21, 6, 13, 6, 11, 5, 6, 10, 11, 11, 21, 17, 23, 10, 36, 4, 4, 7, 23, 6, 12, 2, 7, 5, 14, 3, 10, 5, 9, 43, 38]

How do I create 5 lists of 5 random numbers selected from a list?

From a list of numbers, I'd like to randomly create 5 lists of 5 numbers.
import random
def team():
x = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
y = []
Count = 0
count = 0
while Count < 5:
while count<5:
count += 1
z = random.choice(x)
y += z
x.remove(z)
print(y)
Count +=1
team()
Output:
Expected Output:
I want something like 5 groups of non-repeating numbers
change the code to
import random
def team():
Count = 0
while Count < 5:
x = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
y = []
count = 0
while count<5:
count += 1
z = random.choice(x)
y += z
x.remove(z)
print(y)
Count +=1
team()
in fact, for your original code, the count becomes 5 and break the second for loop. but next time, your count is still 5, so it doesn't go into the second for loop.
You just print the first got y five 5 times.:)
This is a one-liner if you use a nested list comprehension. Also we can just directly sample the integers 0..9 instead of your list of string ['0', '1',...,'9']
import random
teams = [[random.randrange(10) for element in range(5)] for count in range(5)]
# Here's one example run: [[0, 8, 5, 6, 2], [6, 7, 8, 6, 6], [8, 8, 6, 2, 2], [0, 1, 3, 5, 8], [7, 9, 4, 9, 6]]
or if you really want string output instead of ints:
teams = [[str(random.randrange(10)) for element in range(5)] for count in range(5)]
[['3', '8', '2', '5', '3'], ['7', '1', '9', '7', '9'], ['4', '8', '0', '4', '1'], ['7', '6', '5', '8', '2'], ['6', '9', '2', '7', '3']]
or if you really want to randomly sample an arbitrary list of strings:
[ random.sample(['0','1','2','3','4','5','6','7','8','9'], 5) for count in range(5) ]
[['7', '1', '5', '3', '0'], ['7', '1', '6', '2', '8'], ['3', '0', '9', '7', '2'], ['5', '1', '7', '3', '2'], ['6', '2', '5', '0', '3']]

Python- My for loop only converts half the list from str to int

I want my code to cycle through each item of the list and convert it from str to int but it only converts half of the list and in an irregular order.
My code:
for item in list:
list.append(int(item))
list.remove(item)
print (list)
For example if list is ['5', '6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8']
The final would be ['6', '8', '5', '4', '2', '8', 3, 6, 2, 6, 5, 5]
Which is only half converted and not in order.
I could do it another way but that is a lot longer so would like to fix this and add to my knowledge about for loops.
My knowledge and experience with Python is tiny, so I most probably won't understand unless it's really basic and jargon is explained.
Using list comprehension:
l = ['5', '6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8']
output = [int(i) for i in l]
print(output)
[5, 6, 3, 5, 6, 2, 6, 8, 5, 4, 2, 8]
If you don't understand list comprehension you could use simple for loop:
l1 = []
for i in l:
l1.append(int(i))
print(l1)
[5, 6, 3, 5, 6, 2, 6, 8, 5, 4, 2, 8]
Both answers above are good but why your code didn't work also should be adressed.
First , you are changing the list while you are iterating on it. This is something you should not do. It will probably cause problems, like in your question.
Second, remove method removes the first element in the list that it encounters which fits the given argument, it also should be used with care.
Third, you should not use list as an variable name. As it is a built-in class.
for item in list:
print (list)
list.append(int(item))
list.remove(item)
# Prints
['5', '6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8']
['6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8', 5]
['6', '5', '6', '2', '6', '8', '5', '4', '2', '8', 5, 3]
['5', '6', '2', '6', '8', '5', '4', '2', '8', 5, 3, 6]
['5', '2', '6', '8', '5', '4', '2', '8', 5, 3, 6, 6]
['2', '6', '8', '5', '4', '2', '8', 5, 3, 6, 6, 5]
['6', '8', '5', '4', '2', '8', 5, 3, 6, 6, 5, 2]
['6', '8', '5', '4', '2', '8', 3, 6, 6, 5, 2, 5]
['6', '8', '5', '4', '2', '8', 3, 6, 5, 2, 5, 6]
['6', '8', '5', '4', '2', '8', 3, 6, 2, 5, 6, 5]
['6', '8', '5', '4', '2', '8', 3, 6, 2, 6, 5, 5]
['6', '8', '5', '4', '2', '8', 3, 6, 2, 6, 5, 5]
['6', '8', '5', '4', '2', '8', 3, 6, 2, 6, 5, 5]
As you see, not working as expected
Why don't you use something like this:
l = list(map(int, l))
It simply calls function int on each item from l.
Here's doc.
While the other two answers give you better ways of converting your list of strings to integers, they really don't answer your question. Your main problem is that you are mutating (altering) the list structure while your for loop operates on it. You should not mutate the list structure (remove elements or append) because the loop iteration variable item gets out of sync. There's no way to re-sync item to the new list structure.
BTW: It's not a random order. It's every other item.
You could write your conversion loop like so, because you're not mutating the structure of the list, only the individual elements:
for i in xrange(len(l)):
l[i] = int(l[i])
Don't write it like this:
for item in l:
item = int(item)
It doesn't mutate the individual list elements, even though you would think that it does. It has to do with how Python iterators work.
Try this:
>>> list = ['5', '6', '3', '5', '6', '2', '6', '8', '5', '4', '2', '8']
>>> for item in list[:]:
... list.append(int(item))
... list.remove(item)
...
>>> print(list)
[5, 6, 3, 5, 6, 2, 6, 8, 5, 4, 2, 8]
Explanation: Here we are iterating over a clone of the list but doing operations on the original list.
PS: list is a keyword in python. Its usage as a variable name should be avoided.

Changing a list of strings into integers

I have the following list of strings of integers:
li = ['1', '2', '3', '4', '5', '6', '7']
What does my code need to be for my output to be the following?:
1 2 3 4 5 6 7
I tried doing both:
" ".join(str(val) for val in li)
and
" ".join(li)
but both of them don't work.
I want to get rid of the brackets, the quotation marks, and the commas.
You can use map to apply int() to every element in the list:
map(int, ['1', '2', '3', '4', '5', '6', '7']) # [1, 2, 3, 4, 5, 6, 7]
If you just want to print the numbers as a string, you can simply do:
' '.join(['1', '2', '3', '4', '5', '6', '7']) # 1 2 3 4 5 6 7

Categories

Resources