简体   繁体   English

在python中打印多个列表

[英]printing multiple lists in python

Hey I wrote a python code (python 2.7.3) with multiple lists, but when I try to print them they always come with a space. 嘿我写了一个包含多个列表的python代码(python 2.7.3),但是当我尝试打印它们时,它们总是带有空格。 I want to print the list in continuous manner but I'm unable to do so. 我想以连续的方式打印列表,但我无法这样做。 I have one list which have integer values and other with character. 我有一个列表,其中包含整数值,其他列表包含字符。

Eg: list1 (integer list has 123) and list2(character list has ABC). 例如:list1(整数列表有123)和list2(字符列表有ABC)。

Desired Output: ABC123 What I'm getting: ABC 123 期望的输出: ABC123我得到的: ABC 123

What I did: 我做了什么:

print "".join(list2),int("".join(str(x) for x in list1))

Any suggestion what I'm doing wrong? 有什么建议我做错了什么?

l = ["A","B","C"]
l2 = [1,2,3]
print "".join(l+map(str,l2))
ABC123

map casts all ints to str , it is the same as doing [str(x) for x in l2] . map将所有intsstr ,它与[str(x) for x in l2]执行[str(x) for x in l2]

The space comes from the print statement. 空间来自print语句。 It automatically inserts a space between items separated with comma. 它会自动在用逗号分隔的项之间插入空格。 I suppose you don't need to covert the concatenated string into an integer, then you concatenate strings from join and print them as one. 我想你不需要将连接的字符串转换为整数,然后从join连接字符串并将它们打印为一个。

print "".join(list2)+"".join(str(x) for x in list1)

Alternatively you can switch to python3's print function, and use its sep variable. 或者你可以切换到python3的print函数,并使用它的sep变量。

from __future__ import print_function
letters=['A','B','C']
nums=[1,2,3]
print("".join(letters),int("".join(str(x) for x in nums)), sep="")

The , is what's adding the space since you are printing two things, a string 'ABC' and an integer 123. Try using + , which directly adds two strings together so you can print the string 'ABC123' ,是何等的使用增加了空间,因为要打印两件事情,一个字符串“ABC”和一个整数123.尝试+ ,这直接增加了两个字符串,因此您可以打印字符串“ABC123”

>>> list1=[1,2,3]
>>> list2=['A','B','C']
>>> print "".join(list2),int("".join(str(x) for x in list1))
ABC 123
>>> print "".join(list2)+"".join(str(x) for x in list1)
ABC123

Try concatenating the two lists you want while printing. 尝试在打印时连接所需的两个列表。 Use "+" instead of ",". 使用“+”代替“,”。 Here 'int' will give error as you can concatenate only strings. 这里'int'会给出错误,因为你只能连接字符串。 So try, 所以试试吧,

 print "".join(list2)"".join(str(x) for x in list1)

print adds a single space automatically between commas. print在逗号之间自动添加单个空格。

You can use the new print function: 您可以使用新的打印功能:

from __future__ import print_function 
print("".join(list2),int("".join(str(x) for x in list1)), sep="")

See docs . 查看文档

Note: This function is not normally available as a built-in since the name print is recognized as the print statement. 注意:此功能通常不作为内置函数提供,因为名称print被识别为print语句。 To disable the statement and use the print() function, use this future statement at the top of your module 要禁用该语句并使用print()函数,请在模块顶部使用此future语句

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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