简体   繁体   中英

Python-How do I add a space for each odd numbered position in an array?

Essentially, I am inputting a certain number of Xs in an array. However, after that, I want to add a space after each X so that it goes from ['X','X','X','X'] to [X,' ',X,' ',X,' ',X] subject to how many spaces a user enters.

Any help would be appreciated, please.

def two_numbers():

    array = []
    add_x = input('enter no. of x\'s: ')
    add_x = int(add_x)
    for i in range(0,add_x,1):
        array.append('X')


two_numbers()

Just you can append the statement once again.

array = []
add_x = input('enter no. of x\'s: ')
add_x = int(add_x)
for i in range(0,add_x,1):
     array.append('X')
     array.append(" ")


# Multiply the space by the number of spaces you want to append each time.
# array.append(" "*1)

Since you specifically want odd numbered positions with a space, you could do this:

def two_numbers():

    array = []
    add_x = input('enter no. of x\'s: ')
    add_x = int(add_x)
    for i in range(0,add_x,1):
        # Add space if array length is even.
        if len(array) % 2 == 1:
            array.append(' ')
        array.append('X')

two_numbers()

# ['X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X']

Here is a one liner:

num_x = 4
output = list(' '.join('X' * num_x))

print(output)
>>> ['X', ' ', 'X', ' ', 'X', ' ', 'X']

you can use str.join :

add_x = input('enter no. of x\'s: ')
# input 3
array = list(' '.join('X' * add_x)
print(array)

output:

['X', ' ', 'X', ' ', 'X', ' ', 'X']

one-line solution:

array = list(' '.join('X' * int(input('enter no. of x\'s: '))))

or:

array = (['X', ''] * int(input('enter no. of x\'s: ')))[:-1]

just to add other solutions to the ones already here.

import itertools

def two_numbers(n):
    tmp = zip(['X' for _ in range(n)], [' ' for _ in range(n) ])
    return list(itertools.chain(*tmp))

or

def two_numbers(n):
    array = []
    for _ in range(n):
        array += ['X', ' ']
    return array

The returned lists will terminate with a ' ' , if you want to you can remove it by calling the pop method of the list or by returning a slice (eg return array[:-1] )

Solution

Here is a one-line solution to what you want to do.

n = 8 # number of X's
(['X', ' ']*n)[:-1]

Output :

['X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X', ' ', 'X']

Equivalent Other Method(s)

# Method-1
nrep = 5
','.join(['X, ']*nrep)[:-2)].split(',') 

# Method-1 wrapped as a convenience function
def patterned_array(nrep:int = 5, sep = ' ', base_string = 'X') -> list:
    spattern = ''.join([base_string, sep])
    return ','.join(spattern*n)[:-len(spattern)].split(',')

# generate patterned array (a list)
patterned_array(nrep = 8)

Insert a space-character in between elements of an existing list

What if you already have a list of items and they are not necessarily all the same? You could insert a desired character in between those elements in the list as follows.

array = ['a', 'b', 'c', 'd', 'e']
bigarray = [' ']*(len(array)-1)
for i, e in enumerate(array): bigarray.insert(2*i, e)
bigarray

Output :

['a', ' ', 'b', ' ', 'c', ' ', 'd', ' ', 'e']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM