如何“正确”打印列表?

问题:如何“正确”打印列表?

所以我有一个清单:

['x', 3, 'b']

我希望输出为:

[x, 3, b]

如何在python中执行此操作?

如果我这样做str(['x', 3, 'b']),我会用引号引起来,但我不希望引号。

So I have a list:

['x', 3, 'b']

And I want the output to be:

[x, 3, b]

How can I do this in python?

If I do str(['x', 3, 'b']), I get one with quotes, but I don’t want quotes.


回答 0

在Python 2中:

mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))

在Python 3中(其中print是内置函数,而不再是语法功能):

mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))

两者都返回:

[x, 3, b]

这是使用map()函数调用mylist的每个元素的str ,创建一个新的字符串列表,然后用str.join()。然后,%字符串格式运算符将字符串替换为%sin ,而不是in "[%s]"

In Python 2:

mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))

In Python 3 (where print is a builtin function and not a syntax feature anymore):

mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))

Both return:

[x, 3, b]

This is using the map() function to call str for each element of mylist, creating a new list of strings that is then joined into one string with str.join(). Then, the % string formatting operator substitutes the string in instead of %s in "[%s]".


回答 1

这是简单的代码,因此,如果您是新手,则应该足够容易地理解它。

    mylist = ["x", 3, "b"]
    for items in mylist:
        print(items)

如您所愿,它会全部打印不带引号的内容。

This is simple code, so if you are new you should understand it easily enough.

    mylist = ["x", 3, "b"]
    for items in mylist:
        print(items)

It prints all of them without quotes, like you wanted.


回答 2

仅使用打印:

>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b

Using only print:

>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b

回答 3

如果您使用的是Python3:

print('[',end='');print(*L, sep=', ', end='');print(']')

If you are using Python3:

print('[',end='');print(*L, sep=', ', end='');print(']')

回答 4

map建议不要使用join可以接受迭代器的生成器表达式:

def get_nice_string(list_or_iterator):
    return "[" + ", ".join( str(x) for x in list_or_iterator) + "]"

这里join是字符串类的成员函数str。它使用一个参数:一个字符串列表(或迭代器),然后返回一个新字符串,其中所有元素都由串联,

Instead of using map, I’d recommend using a generator expression with the capability of join to accept an iterator:

def get_nice_string(list_or_iterator):
    return "[" + ", ".join( str(x) for x in list_or_iterator) + "]"

Here, join is a member function of the string class str. It takes one argument: a list (or iterator) of strings, then returns a new string with all of the elements concatenated by, in this case, ,.


回答 5

您可以使用它的字符串中删除所有不想要的字符translate()的方法Nonetable参数,随后包含字符(S)你想为它取出一个字符串deletechars参数。

lst = ['x', 3, 'b']

print str(lst).translate(None, "'")

# [x, 3, b]

如果您使用的是2.6之前的Python版本,则需要使用string模块的translate()功能,因为直到2.6才添加了None作为table参数传递的功能。使用它看起来像这样:

import string

print string.translate(str(lst), None, "'")

使用此string.translate()功能在2.6+中也可以使用,因此使用它可能是更可取的。

You can delete all unwanted characters from a string using its translate() method with None for the table argument followed by a string containing the character(s) you want removed for its deletechars argument.

lst = ['x', 3, 'b']

print str(lst).translate(None, "'")

# [x, 3, b]

If you’re using a version of Python before 2.6, you’ll need to use the string module’s translate() function instead because the ability to pass None as the table argument wasn’t added until Python 2.6. Using it looks like this:

import string

print string.translate(str(lst), None, "'")

Using the string.translate() function will also work in 2.6+, so using it might be preferable.


回答 6

这是一个交互式会话,显示了@TokenMacGuy的一线代码中的一些步骤。首先,他使用该map函数将列表中的每个项目转换为字符串(实际上,他正在创建一个新列表,而不是在旧列表中进行转换)。然后,他使用string方法join将这些字符串结合', '在一起。其余的只是字符串格式,这非常简单。(编辑:此实例非常简单;字符串格式通常会有些复杂。)

请注意,使用join是从几个子字符串构建字符串的一种简单而有效的方法,比通过向字符串中连续添加字符串(这样做涉及在幕后进行大量复制)来实现效率要高得多。

>>> mylist = ['x', 3, 'b']
>>> m = map(str, mylist)
>>> m
['x', '3', 'b']
>>> j = ', '.join(m)
>>> j
'x, 3, b'

Here’s an interactive session showing some of the steps in @TokenMacGuy’s one-liner. First he uses the map function to convert each item in the list to a string (actually, he’s making a new list, not converting the items in the old list). Then he’s using the string method join to combine those strings with ', ' between them. The rest is just string formatting, which is pretty straightforward. (Edit: this instance is straightforward; string formatting in general can be somewhat complex.)

Note that using join is a simple and efficient way to build up a string from several substrings, much more efficient than doing it by successively adding strings to strings, which involves a lot of copying behind the scenes.

>>> mylist = ['x', 3, 'b']
>>> m = map(str, mylist)
>>> m
['x', '3', 'b']
>>> j = ', '.join(m)
>>> j
'x, 3, b'

回答 7

使用.format字符串格式化,

mylist = ['x', 3, 'b']
print("[{0}]".format(', '.join(map(str, mylist))))

输出:

[x, 3, b]

说明:

  1. map用于将列表的每个元素映射到string类型。
  2. 这些元素通过,分隔符连接在一起成为一个字符串。
  3. 我们在打印语句中使用[]来显示列表大括号。

参考: .format有关字符串格式PEP-3101

Using .format for string formatting,

mylist = ['x', 3, 'b']
print("[{0}]".format(', '.join(map(str, mylist))))

Output:

[x, 3, b]

Explanation:

  1. map is used to map each element of the list to string type.
  2. The elements are joined together into a string with , as separator.
  3. We use [ and ] in the print statement to show the list braces.

Reference: .format for string formatting PEP-3101


回答 8

@AniMenon启发我编写了一个pythonic更通用的解决方案。

mylist = ['x', 3, 'b']
print('[{}]'.format(', '.join(map('{}'.format, mylist))))

它仅使用该format方法。没有任何痕迹str,并且允许对元素格式进行微调。例如,如果将浮点数作为列表的元素,则在这种情况下,可以通过添加转化说明符来调整其格式:.2f

mylist = [1.8493849, -6.329323, 4000.21222111]
print("[{}]".format(', '.join(map('{:.2f}'.format, mylist))))

输出是相当不错的:

[1.85, -6.33, 4000.21]

I was inspired by @AniMenon to write a pythonic more general solution.

mylist = ['x', 3, 'b']
print('[{}]'.format(', '.join(map('{}'.format, mylist))))

It only uses the format method. No trace of str, and it allows for the fine tuning of the elements format. For example, if you have float numbers as elements of the list, you can adjust their format, by adding a conversion specifier, in this case :.2f

mylist = [1.8493849, -6.329323, 4000.21222111]
print("[{}]".format(', '.join(map('{:.2f}'.format, mylist))))

The output is quite decent:

[1.85, -6.33, 4000.21]