简体   繁体   中英

Print specified number of items in list in Python

I have a list

res = [6, 6, -1, -1, 6]

and I want to print the first v1 characters on one line separated by a space; and the remaining v2 characters on a new line separated by a space.

res = [6, 6, -1, -1, 6]
restemp = res
out = []
v1, v2 = 3, 2
for iii in range(v1):
    out.append(res[iii])
for abc in range(v1):
    restemp.pop(abc)
[print(ou, end=' ') for ou in out]
[print(ttv, end=' ') for ttv in restemp]

this returns

6 6 -1 6 -1

but I want it to return

6 6 -1
6 -1

I tried adding a print('\\n') statement in between but then it returns

6 6 -1

6 -1

You left off the end= in your inserted statement, which means you'll use the default newline. You need to use only one:

print()

or

print('\n', end='')

Even better, try using the join function: join each group into a space-separated string, and then join those with a newline:

out = ' '.join(str(k) for k in res[:v1])
tmp = ' '.join(str(k) for k in res[v2:])
result = '\n'.join(out, tmp)
print(result)

Note that you can link that into one long command ... and then don't do it.

you could use:

print(*out)
print(*restemp)

output:

6 6 -1
6 -1

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