标签归档:list

如何清空列表?

问题:如何清空列表?

用这种方式清空列表似乎太“脏”了:

while len(alist) > 0 : alist.pop()

是否存在明确的方法?

It seems so “dirty” emptying a list in this way:

while len(alist) > 0 : alist.pop()

Does a clear way exist to do that?


回答 0

实际上,这将从列表中删除内容,但不会用新的空列表替换旧标签:

del lst[:]

这是一个例子:

lst1 = [1, 2, 3]
lst2 = lst1
del lst1[:]
print(lst2)

为了完整起见,切片分配具有相同的效果:

lst[:] = []

它也可以用于缩小列表的一部分,同时替换一部分(但这超出了问题的范围)。

请注意,这样lst = []做不会清空列表,只是创建一个新对象并将其绑定到变量lst,但是旧列表仍将具有相同的元素,并且如果具有其他变量绑定,效果将显而易见。

This actually removes the contents from the list, but doesn’t replace the old label with a new empty list:

del lst[:]

Here’s an example:

lst1 = [1, 2, 3]
lst2 = lst1
del lst1[:]
print(lst2)

For the sake of completeness, the slice assignment has the same effect:

lst[:] = []

It can also be used to shrink a part of the list while replacing a part at the same time (but that is out of the scope of the question).

Note that doing lst = [] does not empty the list, just creates a new object and binds it to the variable lst, but the old list will still have the same elements, and effect will be apparent if it had other variable bindings.


回答 1

如果你正在运行的Python 3.3或更好的,你可以使用clear()的方法list,这是平行clear()dictsetdeque和其他易变的容器类型:

alist.clear()  # removes all items from alist (equivalent to del alist[:])

按照链接的文档页面,也可以使用来实现相同的目的alist *= 0

总结起来,有四种等效的方法可以就地清除列表(与PythonZen完全相反!):

  1. alist.clear() # Python 3.3+
  2. del alist[:]
  3. alist[:] = []
  4. alist *= 0

If you’re running Python 3.3 or better, you can use the clear() method of list, which is parallel to clear() of dict, set, deque and other mutable container types:

alist.clear()  # removes all items from alist (equivalent to del alist[:])

As per the linked documentation page, the same can also be achieved with alist *= 0.

To sum up, there are four equivalent ways to clear a list in-place (quite contrary to the Zen of Python!):

  1. alist.clear() # Python 3.3+
  2. del alist[:]
  3. alist[:] = []
  4. alist *= 0

回答 2

您可以尝试:

alist[:] = []

这意味着:在[]位置[:](从头到尾的所有索引)的列表(0个元素)中拼接

[:]是切片运算符。有关更多信息,请参见此问题

You could try:

alist[:] = []

Which means: Splice in the list [] (0 elements) at the location [:] (all indexes from start to finish)

The [:] is the slice operator. See this question for more information.


回答 3

事实证明,使用python 2.5.2的del l[:]速度比l[:] = []使用1.1 usec的速度略慢。

$ python -mtimeit "l=list(range(1000))" "b=l[:];del b[:]"
10000 loops, best of 3: 29.8 usec per loop
$ python -mtimeit "l=list(range(1000))" "b=l[:];b[:] = []"
10000 loops, best of 3: 28.7 usec per loop
$ python -V
Python 2.5.2

it turns out that with python 2.5.2, del l[:] is slightly slower than l[:] = [] by 1.1 usec.

$ python -mtimeit "l=list(range(1000))" "b=l[:];del b[:]"
10000 loops, best of 3: 29.8 usec per loop
$ python -mtimeit "l=list(range(1000))" "b=l[:];b[:] = []"
10000 loops, best of 3: 28.7 usec per loop
$ python -V
Python 2.5.2

回答 4

lst *= 0

与…具有相同的效果

lst[:] = []

它稍微简单一些,也许更容易记住。除此之外,无话可说

效率似乎差不多

lst *= 0

has the same effect as

lst[:] = []

It’s a little simpler and maybe easier to remember. Other than that there’s not much to say

The efficiency seems to be about the same


回答 5

list = []

将重置list为空列表。

请注意,通常您不应该遮盖保留的函数名称,例如list,它是列表对象的构造函数- 例如,可以使用lstlist_代替。

list = []

will reset list to an empty list.

Note that you generally should not shadow reserved function names, such as list, which is the constructor for a list object — you could use lst or list_ instead, for instance.


回答 6

您可以使用的另一个简单代码(取决于您的情况)是:

index=len(list)-1

while index>=0:
    del list[index]
    index-=1

您必须在列表的长度处开始索引,然后相对于索引在0处向前,向后前进,因为这将使您最终获得的索引等于列表的长度,并且仅将其切成两半。

另外,请确保while行上有一个“大于或等于”符号。省略它会使您剩下list [0]。

Another simple code you could use (depending on your situation) is:

index=len(list)-1

while index>=0:
    del list[index]
    index-=1

You have to start index at the length of the list and go backwards versus index at 0, forwards because that would end you up with index equal to the length of the list with it only being cut in half.

Also, be sure that the while line has a “greater than or equal to” sign. Omitting it will leave you with list[0] remaining.


Python-创建数字在2个值之间的列表?

问题:Python-创建数字在2个值之间的列表?

如何创建一个包含两个输入值之间的值的列表?例如,将为11到16的值生成以下列表。

list = [11, 12, 13, 14, 15, 16]

How would I create a list with values between two values I put in? For example, the following list is generated for values from 11 to 16:

list = [11, 12, 13, 14, 15, 16]

回答 0

使用range。在Python 2.x中,它返回一个列表,因此您需要做的是:

>>> range(11, 17)
[11, 12, 13, 14, 15, 16]

在Python 3.x中range是迭代器。因此,您需要将其转换为列表:

>>> list(range(11, 17))
[11, 12, 13, 14, 15, 16]

注意:第二个数字是唯一的。因此,这里需要为16+1=17

编辑:

要回答有关增加by的问题0.5,最简单的选择可能是使用numpy arange().tolist()

>>> import numpy as np
>>> np.arange(11, 17, 0.5).tolist()

[11.0, 11.5, 12.0, 12.5, 13.0, 13.5,
 14.0, 14.5, 15.0, 15.5, 16.0, 16.5]

Use range. In Python 2.x it returns a list so all you need is:

>>> range(11, 17)
[11, 12, 13, 14, 15, 16]

In Python 3.x range is a iterator. So, you need to convert it to a list:

>>> list(range(11, 17))
[11, 12, 13, 14, 15, 16]

Note: The second number is exclusive. So, here it needs to be 16+1 = 17

EDIT:

To respond to the question about incrementing by 0.5, the easiest option would probably be to use numpy’s arange() and .tolist():

>>> import numpy as np
>>> np.arange(11, 17, 0.5).tolist()

[11.0, 11.5, 12.0, 12.5, 13.0, 13.5,
 14.0, 14.5, 15.0, 15.5, 16.0, 16.5]

回答 1

您似乎在寻找range()

>>> x1=11
>>> x2=16
>>> range(x1, x2+1)
[11, 12, 13, 14, 15, 16]
>>> list1 = range(x1, x2+1)
>>> list1
[11, 12, 13, 14, 15, 16]

要以0.5代替递增1,请说:

>>> list2 = [x*0.5 for x in range(2*x1, 2*x2+1)]
>>> list2
[11.0, 11.5, 12.0, 12.5, 13.0, 13.5, 14.0, 14.5, 15.0, 15.5, 16.0]

You seem to be looking for range():

>>> x1=11
>>> x2=16
>>> range(x1, x2+1)
[11, 12, 13, 14, 15, 16]
>>> list1 = range(x1, x2+1)
>>> list1
[11, 12, 13, 14, 15, 16]

For incrementing by 0.5 instead of 1, say:

>>> list2 = [x*0.5 for x in range(2*x1, 2*x2+1)]
>>> list2
[11.0, 11.5, 12.0, 12.5, 13.0, 13.5, 14.0, 14.5, 15.0, 15.5, 16.0]

回答 2

尝试:

range(x1,x2+1)  

那是Python 2.x中的一个列表,其行为与Python 3.x中的一个列表非常相似。如果您正在运行Python 3,并且需要可以修改的列表,请使用:

list(range(x1,x2+1))

Try:

range(x1,x2+1)  

That is a list in Python 2.x and behaves mostly like a list in Python 3.x. If you are running Python 3 and need a list that you can modify, then use:

list(range(x1,x2+1))

回答 3

如果您正在寻找适用于浮点类型的范围之类的函数,那么这是一篇非常不错的文章

def frange(start, stop, step=1.0):
    ''' "range()" like function which accept float type''' 
    i = start
    while i < stop:
        yield i
        i += step
# Generate one element at a time.
# Preferred when you don't need all generated elements at the same time. 
# This will save memory.
for i in frange(1.0, 2.0, 0.5):
    print i   # Use generated element.
# Generate all elements at once.
# Preferred when generated list ought to be small.
print list(frange(1.0, 10.0, 0.5))    

输出:

1.0
1.5
[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5]

If you are looking for range like function which works for float type, then here is a very good article.

def frange(start, stop, step=1.0):
    ''' "range()" like function which accept float type''' 
    i = start
    while i < stop:
        yield i
        i += step
# Generate one element at a time.
# Preferred when you don't need all generated elements at the same time. 
# This will save memory.
for i in frange(1.0, 2.0, 0.5):
    print i   # Use generated element.
# Generate all elements at once.
# Preferred when generated list ought to be small.
print list(frange(1.0, 10.0, 0.5))    

Output:

1.0
1.5
[1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5]

回答 4

在python中使用列表理解。由于您也希望列表中有16个。使用x2 + 1。范围功能不包括该功能的上限。

list = [x表示x在范围(x1,x2 + 1)中]

Use list comprehension in python. Since you want 16 in the list too.. Use x2+1. Range function excludes the higher limit in the function.

list=[x for x in range(x1,x2+1)]


回答 5

假设您希望x到y之间的范围

range(x,y+1)

>>> range(11,17)
[11, 12, 13, 14, 15, 16]
>>>

3.x支持使用列表

assuming you want to have a range between x to y

range(x,y+1)

>>> range(11,17)
[11, 12, 13, 14, 15, 16]
>>>

use list for 3.x support


回答 6

在python中,您可以非常轻松地执行此操作

start=0
end=10
arr=list(range(start,end+1))
output: arr=[0,1,2,3,4,5,6,7,8,9,10]

或者,您可以创建一个递归函数,该函数返回一个数组,并返回给定的数字:

ar=[]
def diff(start,end):
    if start==end:
        d.append(end)
        return ar
    else:
        ar.append(end)
        return diff(start-1,end) 

输出:ar = [10,9,8,7,6,5,4,3,2,1,0]

In python you can do this very eaisly

start=0
end=10
arr=list(range(start,end+1))
output: arr=[0,1,2,3,4,5,6,7,8,9,10]

or you can create a recursive function that returns an array upto a given number:

ar=[]
def diff(start,end):
    if start==end:
        d.append(end)
        return ar
    else:
        ar.append(end)
        return diff(start-1,end) 

output: ar=[10,9,8,7,6,5,4,3,2,1,0]


回答 7

最优雅的方法是使用range函数,但是,如果您想重新创建此逻辑,则可以执行以下操作:

def custom_range(*args):
    s = slice(*args)
    start, stop, step = s.start, s.stop, s.step
    if 0 == step:
        raise ValueError("range() arg 3 must not be zero")
    i = start
    while i < stop if step > 0 else i > stop:
        yield i
        i += step

>>> [x for x in custom_range(10, 3, -1)]

产生输出:

[10, 9, 8, 7, 6, 5, 4]

正如之前@Jared表示,最好的办法是使用rangenumpy.arrange不过,我觉得要共享的代码有趣。

The most elegant way to do this is by using the range function however if you want to re-create this logic you can do something like this :

def custom_range(*args):
    s = slice(*args)
    start, stop, step = s.start, s.stop, s.step
    if 0 == step:
        raise ValueError("range() arg 3 must not be zero")
    i = start
    while i < stop if step > 0 else i > stop:
        yield i
        i += step

>>> [x for x in custom_range(10, 3, -1)]

This produces the output:

[10, 9, 8, 7, 6, 5, 4]

As expressed before by @Jared, the best way is to use the range or numpy.arrange however I find the code interesting to be shared.


回答 8

上面的每个答案都假定范围仅是正数。这是返回连续数字列表的解决方案,其中参数可以是任意值(正数或负数),并且可以设置可选的步长值(默认值= 1)。

def any_number_range(a,b,s=1):
""" Generate consecutive values list between two numbers with optional step (default=1)."""
if (a == b):
    return a
else:
    mx = max(a,b)
    mn = min(a,b)
    result = []
    # inclusive upper limit. If not needed, delete '+1' in the line below
    while(mn < mx + 1):
        # if step is positive we go from min to max
        if s > 0:
            result.append(mn)
            mn += s
        # if step is negative we go from max to min
        if s < 0:
            result.append(mx)
            mx += s
    return result

例如,标准命令list(range(1,-3))返回空列表[],而此函数将返回[-3,-2,-1,0,1]

更新:现在步骤可能为负。感谢@Michael的评论。

Every answer above assumes range is of positive numbers only. Here is the solution to return list of consecutive numbers where arguments can be any (positive or negative), with the possibility to set optional step value (default = 1).

def any_number_range(a,b,s=1):
""" Generate consecutive values list between two numbers with optional step (default=1)."""
if (a == b):
    return a
else:
    mx = max(a,b)
    mn = min(a,b)
    result = []
    # inclusive upper limit. If not needed, delete '+1' in the line below
    while(mn < mx + 1):
        # if step is positive we go from min to max
        if s > 0:
            result.append(mn)
            mn += s
        # if step is negative we go from max to min
        if s < 0:
            result.append(mx)
            mx += s
    return result

For instance, standard command list(range(1,-3)) returns empty list [], while this function will return [-3,-2,-1,0,1]

Updated: now step may be negative. Thanks @Michael for his comment.


如何从字典中获取值列表?

问题:如何从字典中获取值列表?

如何在Python中获取字典中的值列表?

在Java中,将Map的值作为List变得容易list = map.values();。我想知道Python中是否有类似的简单方法可以从字典中获取值列表。

How can I get a list of the values in a dict in Python?

In Java, getting the values of a Map as a List is as easy as doing list = map.values();. I’m wondering if there is a similarly simple way in Python to get a list of values from a dict.


回答 0

是的,这与Python 2完全相同:

d.values()

Python 3中(在其中dict.values返回字典值的视图):

list(d.values())

Yes it’s the exact same thing in Python 2:

d.values()

In Python 3 (where dict.values returns a view of the dictionary’s values instead):

list(d.values())

回答 1

您可以使用*运算符解压缩dict_values:

>>> d = {1: "a", 2: "b"}
>>> [*d.values()]
['a', 'b']

或列出对象

>>> d = {1: "a", 2: "b"}
>>> list(d.values())
['a', 'b']

You can use * operator to unpack dict_values:

>>> d = {1: "a", 2: "b"}
>>> [*d.values()]
['a', 'b']

or list object

>>> d = {1: "a", 2: "b"}
>>> list(d.values())
['a', 'b']

回答 2

应该有一种方法,最好只有一种方法。

因此list(dictionary.values())一种方法

但是,考虑到Python3,更快的方法是什么?

[*L]vs. [].extend(L)vs.list(L)

small_ds = {x: str(x+42) for x in range(10)}
small_df = {x: float(x+42) for x in range(10)}

print('Small Dict(str)')
%timeit [*small_ds.values()]
%timeit [].extend(small_ds.values())
%timeit list(small_ds.values())

print('Small Dict(float)')
%timeit [*small_df.values()]
%timeit [].extend(small_df.values())
%timeit list(small_df.values())

big_ds = {x: str(x+42) for x in range(1000000)}
big_df = {x: float(x+42) for x in range(1000000)}

print('Big Dict(str)')
%timeit [*big_ds.values()]
%timeit [].extend(big_ds.values())
%timeit list(big_ds.values())

print('Big Dict(float)')
%timeit [*big_df.values()]
%timeit [].extend(big_df.values())
%timeit list(big_df.values())
Small Dict(str)
256 ns ± 3.37 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
338 ns ± 0.807 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
336 ns ± 1.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Small Dict(float)
268 ns ± 0.297 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
343 ns ± 15.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
336 ns ± 0.68 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Big Dict(str)
17.5 ms ± 142 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
16.5 ms ± 338 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
16.2 ms ± 19.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Big Dict(float)
13.2 ms ± 41 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
13.1 ms ± 919 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
12.8 ms ± 578 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

在Intel®Core™i7-8650U CPU @ 1.90GHz上完成。

# Name                    Version                   Build
ipython                   7.5.0            py37h24bf2e0_0

结果

  1. 对于小词典* operator更快
  2. 对于重要的大字典来说,list()可能会更快

There should be one ‒ and preferably only one ‒ obvious way to do it.

Therefore list(dictionary.values()) is the one way.

Yet, considering Python3, what is quicker?

[*L] vs. [].extend(L) vs. list(L)

small_ds = {x: str(x+42) for x in range(10)}
small_df = {x: float(x+42) for x in range(10)}

print('Small Dict(str)')
%timeit [*small_ds.values()]
%timeit [].extend(small_ds.values())
%timeit list(small_ds.values())

print('Small Dict(float)')
%timeit [*small_df.values()]
%timeit [].extend(small_df.values())
%timeit list(small_df.values())

big_ds = {x: str(x+42) for x in range(1000000)}
big_df = {x: float(x+42) for x in range(1000000)}

print('Big Dict(str)')
%timeit [*big_ds.values()]
%timeit [].extend(big_ds.values())
%timeit list(big_ds.values())

print('Big Dict(float)')
%timeit [*big_df.values()]
%timeit [].extend(big_df.values())
%timeit list(big_df.values())
Small Dict(str)
256 ns ± 3.37 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
338 ns ± 0.807 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
336 ns ± 1.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Small Dict(float)
268 ns ± 0.297 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
343 ns ± 15.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
336 ns ± 0.68 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Big Dict(str)
17.5 ms ± 142 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
16.5 ms ± 338 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
16.2 ms ± 19.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Big Dict(float)
13.2 ms ± 41 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
13.1 ms ± 919 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
12.8 ms ± 578 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Done on Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz.

# Name                    Version                   Build
ipython                   7.5.0            py37h24bf2e0_0

The result

  1. For small dictionaries * operator is quicker
  2. For big dictionaries where it matters list() is maybe slightly quicker

回答 3

请按照以下示例-

songs = [
{"title": "happy birthday", "playcount": 4},
{"title": "AC/DC", "playcount": 2},
{"title": "Billie Jean", "playcount": 6},
{"title": "Human Touch", "playcount": 3}
]

print("====================")
print(f'Songs --> {songs} \n')
title = list(map(lambda x : x['title'], songs))
print(f'Print Title --> {title}')

playcount = list(map(lambda x : x['playcount'], songs))
print(f'Print Playcount --> {playcount}')
print (f'Print Sorted playcount --> {sorted(playcount)}')

# Aliter -
print(sorted(list(map(lambda x: x['playcount'],songs))))

Follow the below example —

songs = [
{"title": "happy birthday", "playcount": 4},
{"title": "AC/DC", "playcount": 2},
{"title": "Billie Jean", "playcount": 6},
{"title": "Human Touch", "playcount": 3}
]

print("====================")
print(f'Songs --> {songs} \n')
title = list(map(lambda x : x['title'], songs))
print(f'Print Title --> {title}')

playcount = list(map(lambda x : x['playcount'], songs))
print(f'Print Playcount --> {playcount}')
print (f'Print Sorted playcount --> {sorted(playcount)}')

# Aliter -
print(sorted(list(map(lambda x: x['playcount'],songs))))

回答 4

out: dict_values([{1:a, 2:b}])

in:  str(dict.values())[14:-3]    
out: 1:a, 2:b

纯粹出于视觉目的。不会产生有用的产品…仅在您希望长字典以段落类型形式打印时才有用。

out: dict_values([{1:a, 2:b}])

in:  str(dict.values())[14:-3]    
out: 1:a, 2:b

Purely for visual purposes. Does not produce a useful product… Only useful if you want a long dictionary to print in a paragraph type form.


将列表中的所有字符串转换为int

问题:将列表中的所有字符串转换为int

在Python中,我想将列表中的所有字符串转换为整数。

所以,如果我有:

results = ['1', '2', '3']

我该如何做:

results = [1, 2, 3]

In Python, I want to convert all strings in a list to integers.

So if I have:

results = ['1', '2', '3']

How do I make it:

results = [1, 2, 3]

回答 0

使用map功能(在Python 2.x中):

results = map(int, results)

在Python 3中,您需要将结果从map转换为列表:

results = list(map(int, results))

Use the map function (in Python 2.x):

results = map(int, results)

In Python 3, you will need to convert the result from map to a list:

results = list(map(int, results))

回答 1

使用列表理解

results = [int(i) for i in results]

例如

>>> results = ["1", "2", "3"]
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]

Use a list comprehension:

results = [int(i) for i in results]

e.g.

>>> results = ["1", "2", "3"]
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]

回答 2

比列表理解要扩展一点,但同样有用:

def str_list_to_int_list(str_list):
    n = 0
    while n < len(str_list):
        str_list[n] = int(str_list[n])
        n += 1
    return(str_list)

例如

>>> results = ["1", "2", "3"]
>>> str_list_to_int_list(results)
[1, 2, 3]

也:

def str_list_to_int_list(str_list):
    int_list = [int(n) for n in str_list]
    return int_list

A little bit more expanded than list comprehension but likewise useful:

def str_list_to_int_list(str_list):
    n = 0
    while n < len(str_list):
        str_list[n] = int(str_list[n])
        n += 1
    return(str_list)

e.g.

>>> results = ["1", "2", "3"]
>>> str_list_to_int_list(results)
[1, 2, 3]

Also:

def str_list_to_int_list(str_list):
    int_list = [int(n) for n in str_list]
    return int_list

如何将字符串拆分为列表?

问题:如何将字符串拆分为列表?

我希望我的Python函数拆分一个句子(输入)并将每个单词存储在列表中。我当前的代码拆分了句子,但没有将单词存储为列表。我怎么做?

def split_line(text):

    # split the text
    words = text.split()

    # for each word in the line:
    for word in words:

        # print the word
        print(words)

I want my Python function to split a sentence (input) and store each word in a list. My current code splits the sentence, but does not store the words as a list. How do I do that?

def split_line(text):

    # split the text
    words = text.split()

    # for each word in the line:
    for word in words:

        # print the word
        print(words)

回答 0

text.split()

这应该足以将每个单词存储在列表中。 words已经是句子中单词的列表,因此不需要循环。

其次,这可能是一个错字,但是您的循环有点混乱。如果您确实确实想使用附加,它将是:

words.append(word)

word.append(words)
text.split()

This should be enough to store each word in a list. words is already a list of the words from the sentence, so there is no need for the loop.

Second, it might be a typo, but you have your loop a little messed up. If you really did want to use append, it would be:

words.append(word)

not

word.append(words)

回答 1

text在任何连续的空格运行中拆分字符串。

words = text.split()      

text在分隔符上分割字符串","

words = text.split(",")   

单词变量将为a,list并包含text分隔符上的split 单词。

Splits the string in text on any consecutive runs of whitespace.

words = text.split()      

Split the string in text on delimiter: ",".

words = text.split(",")   

The words variable will be a list and contain the words from text split on the delimiter.


回答 2

str.split()

返回字符串中的单词列表,使用sep作为定界符…如果未指定sep或为None,则应用不同的拆分算法:连续空格的运行被视为单个分隔符,并且结果将包含如果字符串的开头或结尾有空格,则开头或结尾不得有空字符串。

>>> line="a sentence with a few words"
>>> line.split()
['a', 'sentence', 'with', 'a', 'few', 'words']
>>> 

str.split()

Return a list of the words in the string, using sep as the delimiter … If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

>>> line="a sentence with a few words"
>>> line.split()
['a', 'sentence', 'with', 'a', 'few', 'words']
>>> 

回答 3

根据您打算如何处理列表中的句子,您可能需要查看Natural Language Took Kit。它主要处理文本处理和评估。您也可以使用它来解决您的问题:

import nltk
words = nltk.word_tokenize(raw_sentence)

这具有将标点符号分开的额外好处。

例:

>>> import nltk
>>> s = "The fox's foot grazed the sleeping dog, waking it."
>>> words = nltk.word_tokenize(s)
>>> words
['The', 'fox', "'s", 'foot', 'grazed', 'the', 'sleeping', 'dog', ',', 
'waking', 'it', '.']

这使您可以过滤掉不需要的标点,而仅使用单词。

请注意,string.split()如果您不打算对句子进行任何复杂的处理,则使用其他解决方案会更好。

[编辑]

Depending on what you plan to do with your sentence-as-a-list, you may want to look at the Natural Language Took Kit. It deals heavily with text processing and evaluation. You can also use it to solve your problem:

import nltk
words = nltk.word_tokenize(raw_sentence)

This has the added benefit of splitting out punctuation.

Example:

>>> import nltk
>>> s = "The fox's foot grazed the sleeping dog, waking it."
>>> words = nltk.word_tokenize(s)
>>> words
['The', 'fox', "'s", 'foot', 'grazed', 'the', 'sleeping', 'dog', ',', 
'waking', 'it', '.']

This allows you to filter out any punctuation you don’t want and use only words.

Please note that the other solutions using string.split() are better if you don’t plan on doing any complex manipulation of the sentence.

[Edited]


回答 4

这个算法怎么样?在空白处分割文本,然后修剪标点符号。这会仔细删除单词边缘的标点符号,而不会损害单词内的撇号,例如we're

>>> text
"'Oh, you can't help that,' said the Cat: 'we're all mad here. I'm mad. You're mad.'"

>>> text.split()
["'Oh,", 'you', "can't", 'help', "that,'", 'said', 'the', 'Cat:', "'we're", 'all', 'mad', 'here.', "I'm", 'mad.', "You're", "mad.'"]

>>> import string
>>> [word.strip(string.punctuation) for word in text.split()]
['Oh', 'you', "can't", 'help', 'that', 'said', 'the', 'Cat', "we're", 'all', 'mad', 'here', "I'm", 'mad', "You're", 'mad']

How about this algorithm? Split text on whitespace, then trim punctuation. This carefully removes punctuation from the edge of words, without harming apostrophes inside words such as we're.

>>> text
"'Oh, you can't help that,' said the Cat: 'we're all mad here. I'm mad. You're mad.'"

>>> text.split()
["'Oh,", 'you', "can't", 'help', "that,'", 'said', 'the', 'Cat:', "'we're", 'all', 'mad', 'here.', "I'm", 'mad.', "You're", "mad.'"]

>>> import string
>>> [word.strip(string.punctuation) for word in text.split()]
['Oh', 'you', "can't", 'help', 'that', 'said', 'the', 'Cat', "we're", 'all', 'mad', 'here', "I'm", 'mad', "You're", 'mad']

回答 5

我希望我的python函数拆分一个句子(输入)并将每个单词存储在列表中

str().split()方法执行此操作,它需要一个字符串,并将其拆分为一个列表:

>>> the_string = "this is a sentence"
>>> words = the_string.split(" ")
>>> print(words)
['this', 'is', 'a', 'sentence']
>>> type(words)
<type 'list'> # or <class 'list'> in Python 3.0

您遇到的问题是由于输入错误,print(words)而不是您写的print(word)

word变量重命名为current_word,这就是您所拥有的:

def split_line(text):
    words = text.split()
    for current_word in words:
        print(words)

..什么时候应该完成:

def split_line(text):
    words = text.split()
    for current_word in words:
        print(current_word)

如果出于某种原因要在for循环中手动构造列表,则可以使用list append()方法,也许是因为您想对所有单词都小写(例如):

my_list = [] # make empty list
for current_word in words:
    my_list.append(current_word.lower())

或者使用list-comprehension更加整洁:

my_list = [current_word.lower() for current_word in words]

I want my python function to split a sentence (input) and store each word in a list

The str().split() method does this, it takes a string, splits it into a list:

>>> the_string = "this is a sentence"
>>> words = the_string.split(" ")
>>> print(words)
['this', 'is', 'a', 'sentence']
>>> type(words)
<type 'list'> # or <class 'list'> in Python 3.0

The problem you’re having is because of a typo, you wrote print(words) instead of print(word):

Renaming the word variable to current_word, this is what you had:

def split_line(text):
    words = text.split()
    for current_word in words:
        print(words)

..when you should have done:

def split_line(text):
    words = text.split()
    for current_word in words:
        print(current_word)

If for some reason you want to manually construct a list in the for loop, you would use the list append() method, perhaps because you want to lower-case all words (for example):

my_list = [] # make empty list
for current_word in words:
    my_list.append(current_word.lower())

Or more a bit neater, using a list-comprehension:

my_list = [current_word.lower() for current_word in words]

回答 6

shlex具有.split()功能。它的不同之处str.split()在于,它不保留引号,并且将带引号的词组视为一个单词:

>>> import shlex
>>> shlex.split("sudo echo 'foo && bar'")
['sudo', 'echo', 'foo && bar']

shlex has a .split() function. It differs from str.split() in that it does not preserve quotes and treats a quoted phrase as a single word:

>>> import shlex
>>> shlex.split("sudo echo 'foo && bar'")
['sudo', 'echo', 'foo && bar']

回答 7

如果要在列表中包含单词/句子的所有字符,请执行以下操作:

print(list("word"))
#  ['w', 'o', 'r', 'd']


print(list("some sentence"))
#  ['s', 'o', 'm', 'e', ' ', 's', 'e', 'n', 't', 'e', 'n', 'c', 'e']

If you want all the chars of a word/sentence in a list, do this:

print(list("word"))
#  ['w', 'o', 'r', 'd']


print(list("some sentence"))
#  ['s', 'o', 'm', 'e', ' ', 's', 'e', 'n', 't', 'e', 'n', 'c', 'e']

回答 8

我认为您因错字而感到困惑。

更换print(words)print(word)您的循环内已印刷在另一条线路的每一个字

I think you are confused because of a typo.

Replace print(words) with print(word) inside your loop to have every word printed on a different line


将列表中的项目连接到字符串

问题:将列表中的项目连接到字符串

有没有更简单的方法将列表中的字符串项连接为单个字符串?我可以使用该str.join()功能吗?

例如,这是输入['this','is','a','sentence'],这是所需的输出this-is-a-sentence

sentence = ['this','is','a','sentence']
sent_str = ""
for i in sentence:
    sent_str += str(i) + "-"
sent_str = sent_str[:-1]
print sent_str

Is there a simpler way to concatenate string items in a list into a single string? Can I use the str.join() function?

E.g. this is the input ['this','is','a','sentence'] and this is the desired output this-is-a-sentence

sentence = ['this','is','a','sentence']
sent_str = ""
for i in sentence:
    sent_str += str(i) + "-"
sent_str = sent_str[:-1]
print sent_str

回答 0

用途join

>>> sentence = ['this','is','a','sentence']
>>> '-'.join(sentence)
'this-is-a-sentence'

Use join:

>>> sentence = ['this','is','a','sentence']
>>> '-'.join(sentence)
'this-is-a-sentence'

回答 1

将python列表转换为字符串的更通用的方法是:

>>> my_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> my_lst_str = ''.join(map(str, my_lst))
>>> print(my_lst_str)
'12345678910'

A more generic way to convert python lists to strings would be:

>>> my_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> my_lst_str = ''.join(map(str, my_lst))
>>> print(my_lst_str)
'12345678910'

回答 2

对于初学者来说,了解join为什么是字符串方法非常有用 。

一开始很奇怪,但此后非常有用。

连接的结果始终是一个字符串,但是要连接的对象可以有多种类型(生成器,列表,元组等)。

.join更快,因为它只分配一次内存。比经典串联更好(请参阅扩展说明)。

一旦学习了它,它就会非常舒适,您可以执行以下技巧来添加括号。

>>> ",".join("12345").join(("(",")"))
Out:
'(1,2,3,4,5)'

>>> list = ["(",")"]
>>> ",".join("12345").join(list)
Out:
'(1,2,3,4,5)'

It’s very useful for beginners to know why join is a string method.

It’s very strange at the beginning, but very useful after this.

The result of join is always a string, but the object to be joined can be of many types (generators, list, tuples, etc).

.join is faster because it allocates memory only once. Better than classical concatenation (see, extended explanation).

Once you learn it, it’s very comfortable and you can do tricks like this to add parentheses.

>>> ",".join("12345").join(("(",")"))
Out:
'(1,2,3,4,5)'

>>> list = ["(",")"]
>>> ",".join("12345").join(list)
Out:
'(1,2,3,4,5)'

回答 3

尽管@Burhan Khalid的回答很好,但我认为这样更容易理解:

from str import join

sentence = ['this','is','a','sentence']

join(sentence, "-") 

join()的第二个参数是可选的,默认为“”。

编辑:此功能已在Python 3中删除

Although @Burhan Khalid’s answer is good, I think it’s more understandable like this:

from str import join

sentence = ['this','is','a','sentence']

join(sentence, "-") 

The second argument to join() is optional and defaults to ” “.

EDIT: This function was removed in Python 3


回答 4

我们可以指定如何连接字符串。除了使用’-‘,我们还可以使用”

sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)

We can specify how we have to join the string. Instead of ‘-‘, we can use ‘ ‘

sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)

回答 5

我们还可以使用Python的reduce函数:

from functools import reduce

sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)

We can also use Python’s reduce function:

from functools import reduce

sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)

回答 6

def eggs(someParameter):
    del spam[3]
    someParameter.insert(3, ' and cats.')


spam = ['apples', 'bananas', 'tofu', 'cats']
eggs(spam)
spam =(','.join(spam))
print(spam)
def eggs(someParameter):
    del spam[3]
    someParameter.insert(3, ' and cats.')


spam = ['apples', 'bananas', 'tofu', 'cats']
eggs(spam)
spam =(','.join(spam))
print(spam)

在python中创建具有特定大小的空列表

问题:在python中创建具有特定大小的空列表

我想创建一个可以容纳10个元素的空列表(或最好的方法)。

之后,我想在该列表中分配值,例如,应该显示0到9:

s1 = list();
for i in range(0,9):
   s1[i] = i

print  s1

但是当我运行此代码时,它会生成错误,或者在其他情况下,它只会显示 [](空)。

有人可以解释为什么吗?

I want to create an empty list (or whatever is the best way) that can hold 10 elements.

After that I want to assign values in that list, for example this is supposed to display 0 to 9:

s1 = list();
for i in range(0,9):
   s1[i] = i

print  s1

But when I run this code, it generates an error or in another case it just displays [] (empty).

Can someone explain why?


回答 0

您不能分配给类似的列表lst[i] = something,除非该列表已至少已使用i+1元素初始化。您需要使用append将元素添加到列表的末尾。lst.append(something)

(如果使用字典,则可以使用分配符号)。

创建一个空列表:

>>> l = [None] * 10
>>> l
[None, None, None, None, None, None, None, None, None, None]

为上述列表的现有元素分配一个值:

>>> l[1] = 5
>>> l
[None, 5, None, None, None, None, None, None, None, None]

请记住,类似 l[15] = 5仍然会失败,因为我们的列表只有10个元素。

range(x)从[0,1,2,… x-1]创建一个列表

# 2.X only. Use list(range(10)) in 3.X.
>>> l = range(10)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

使用函数创建列表:

>>> def display():
...     s1 = []
...     for i in range(9): # This is just to tell you how to create a list.
...         s1.append(i)
...     return s1
... 
>>> print display()
[0, 1, 2, 3, 4, 5, 6, 7, 8]

列表理解(使用正方形,因为对于范围您不需要执行所有这些操作,您只需返回即可range(0,9)):

>>> def display():
...     return [x**2 for x in range(9)]
... 
>>> print display()
[0, 1, 4, 9, 16, 25, 36, 49, 64]

You cannot assign to a list like lst[i] = something, unless the list already is initialized with at least i+1 elements. You need to use append to add elements to the end of the list. lst.append(something).

(You could use the assignment notation if you were using a dictionary).

Creating an empty list:

>>> l = [None] * 10
>>> l
[None, None, None, None, None, None, None, None, None, None]

Assigning a value to an existing element of the above list:

>>> l[1] = 5
>>> l
[None, 5, None, None, None, None, None, None, None, None]

Keep in mind that something like l[15] = 5 would still fail, as our list has only 10 elements.

range(x) creates a list from [0, 1, 2, … x-1]

# 2.X only. Use list(range(10)) in 3.X.
>>> l = range(10)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Using a function to create a list:

>>> def display():
...     s1 = []
...     for i in range(9): # This is just to tell you how to create a list.
...         s1.append(i)
...     return s1
... 
>>> print display()
[0, 1, 2, 3, 4, 5, 6, 7, 8]

List comprehension (Using the squares because for range you don’t need to do all this, you can just return range(0,9) ):

>>> def display():
...     return [x**2 for x in range(9)]
... 
>>> print display()
[0, 1, 4, 9, 16, 25, 36, 49, 64]

回答 1

尝试以下方法:

lst = [None] * 10

上面将创建一个大小为10的列表,其中每个位置都初始化为None。之后,您可以向其中添加元素:

lst = [None] * 10
for i in range(10):
    lst[i] = i

诚然,这不是Python的做事方式。最好这样做:

lst = []
for i in range(10):
    lst.append(i)

更简单的一点是,在Python 2.x中,您可以执行以下操作以初始化值从0到9的列表:

lst = range(10)

在Python 3.x中:

lst = list(range(10))

Try this instead:

lst = [None] * 10

The above will create a list of size 10, where each position is initialized to None. After that, you can add elements to it:

lst = [None] * 10
for i in range(10):
    lst[i] = i

Admittedly, that’s not the Pythonic way to do things. Better do this:

lst = []
for i in range(10):
    lst.append(i)

Or even simpler, in Python 2.x you can do this to initialize a list with values from 0 to 9:

lst = range(10)

And in Python 3.x:

lst = list(range(10))

回答 2

varunl当前接受的答案

 >>> l = [None] * 10
 >>> l
 [None, None, None, None, None, None, None, None, None, None]

对于数字等非引用类型,效果很好。不幸的是,如果您要创建列表列表,则会遇到引用错误。Python 2.7.6中的示例:

>>> a = [[]]*10
>>> a
[[], [], [], [], [], [], [], [], [], []]
>>> a[0].append(0)
>>> a
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]
>>> 

如您所见,每个元素都指向相同的列表对象。为了解决这个问题,您可以创建一个将每个位置初始化为不同对象引用的方法。

def init_list_of_objects(size):
    list_of_objects = list()
    for i in range(0,size):
        list_of_objects.append( list() ) #different object reference each time
    return list_of_objects


>>> a = init_list_of_objects(10)
>>> a
[[], [], [], [], [], [], [], [], [], []]
>>> a[0].append(0)
>>> a
[[0], [], [], [], [], [], [], [], [], []]
>>> 

可能有一种默认的内置python方式(而不是编写函数)来执行此操作,但是我不确定它是什么。很高兴得到纠正!

编辑:这是 [ [] for _ in range(10)]

范例:

>>> [ [random.random() for _ in range(2) ] for _ in range(5)]
>>> [[0.7528051908943816, 0.4325669600055032], [0.510983236521753, 0.7789949902294716], [0.09475179523690558, 0.30216475640534635], [0.3996890132468158, 0.6374322093017013], [0.3374204010027543, 0.4514925173253973]]

varunl’s currently accepted answer

 >>> l = [None] * 10
 >>> l
 [None, None, None, None, None, None, None, None, None, None]

Works well for non-reference types like numbers. Unfortunately if you want to create a list-of-lists you will run into referencing errors. Example in Python 2.7.6:

>>> a = [[]]*10
>>> a
[[], [], [], [], [], [], [], [], [], []]
>>> a[0].append(0)
>>> a
[[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]
>>> 

As you can see, each element is pointing to the same list object. To get around this, you can create a method that will initialize each position to a different object reference.

def init_list_of_objects(size):
    list_of_objects = list()
    for i in range(0,size):
        list_of_objects.append( list() ) #different object reference each time
    return list_of_objects


>>> a = init_list_of_objects(10)
>>> a
[[], [], [], [], [], [], [], [], [], []]
>>> a[0].append(0)
>>> a
[[0], [], [], [], [], [], [], [], [], []]
>>> 

There is likely a default, built-in python way of doing this (instead of writing a function), but I’m not sure what it is. Would be happy to be corrected!

Edit: It’s [ [] for _ in range(10)]

Example :

>>> [ [random.random() for _ in range(2) ] for _ in range(5)]
>>> [[0.7528051908943816, 0.4325669600055032], [0.510983236521753, 0.7789949902294716], [0.09475179523690558, 0.30216475640534635], [0.3996890132468158, 0.6374322093017013], [0.3374204010027543, 0.4514925173253973]]

回答 3

您可以.append(element)进入列表,例如:s1.append(i)。您当前要执行的操作是访问s1[i]不存在的元素()。

You can .append(element) to the list, e.g.: s1.append(i). What you are currently trying to do is access an element (s1[i]) that does not exist.


回答 4

有两种“快速”方法:

x = length_of_your_list
a = [None]*x
# or
a = [None for _ in xrange(x)]

似乎[None]*x更快:

>>> from timeit import timeit
>>> timeit("[None]*100",number=10000)
0.023542165756225586
>>> timeit("[None for _ in xrange(100)]",number=10000)
0.07616496086120605

但是,如果您可以接受范围(例如[0,1,2,3,...,x-1]),则range(x)可能最快:

>>> timeit("range(100)",number=10000)
0.012513160705566406

There are two “quick” methods:

x = length_of_your_list
a = [None]*x
# or
a = [None for _ in xrange(x)]

It appears that [None]*x is faster:

>>> from timeit import timeit
>>> timeit("[None]*100",number=10000)
0.023542165756225586
>>> timeit("[None for _ in xrange(100)]",number=10000)
0.07616496086120605

But if you are ok with a range (e.g. [0,1,2,3,...,x-1]), then range(x) might be fastest:

>>> timeit("range(100)",number=10000)
0.012513160705566406

回答 5

我很惊讶没有人建议使用这种简单的方法来创建一个空列表。这是一个旧线程,但仅出于完整性目的添加它。这将创建一个包含10个空列表的列表

x = [[] for i in range(10)]

I’m surprised nobody suggest this simple approach to creating a list of empty lists. This is an old thread, but just adding this for completeness. This will create a list of 10 empty lists

x = [[] for i in range(10)]

回答 6

(这是根据问题的原始版本编写的。)

我想创建一个空列表(或最好的方法)以容纳10个元素。

所有列表可以容纳任意数量的元素,仅受可用内存的限制。列表中唯一重要的“大小”是当前列表中的元素数量。

但是当我运行它时,结果是[]

print display s1语法无效;根据您对所看到内容的描述,我认为您的意思是display(s1)然后print s1。为此,您必须预先定义一个全局s1变量以传递给该函数。

呼叫display并不会像书面那样修改您传入的列表。您的代码说:“ s1是传递给函数的任何事物的名称;好的,现在我们要做的第一件事是完全忘记该事物,让我们s1开始引用一个新创建的事物list。现在我们将对其进行修改。list ”。这对您传递的值没有影响。

没有理由在此处传递值。(创建一个函数也没有真正的理由,但这并不重要。)您想“创建”某些东西,这就是函数的输出。创建您所描述的事物不需要任何信息,因此请勿传递任何信息。要获取信息,return它。

那会给你类似的东西:

def display():
    s1 = list();
    for i in range(0, 9):
        s1[i] = i
    return s1

您将要注意的下一个问题是列表实际上仅包含9个元素,因为该range函数跳过了终点。(作为旁注,其[]效果与一样好list(),并且不需要分号,它s1是变量的较差名称,并且range如果从0。开始,则只需要一个参数。)因此,最后得到

def create_list():
    result = list()
    for i in range(10):
        result[i] = i
    return result

但是,这仍然没有实现。range是不是这就是语言的一部分的方式一些神奇的关键字fordef是,而是它的一个功能。猜猜该函数返回什么?没错-这些整数的列表。所以整个功能都崩溃了

def create_list():
    return range(10)

现在您了解了为什么我们根本不需要自己编写函数;range已经是我们要寻找的功能。同样,尽管没有必要或没有理由“调整”列表大小。

(This was written based on the original version of the question.)

I want to create a empty list (or whatever is the best way) can hold 10 elements.

All lists can hold as many elements as you like, subject only to the limit of available memory. The only “size” of a list that matters is the number of elements currently in it.

but when I run it, the result is []

print display s1 is not valid syntax; based on your description of what you’re seeing, I assume you meant display(s1) and then print s1. For that to run, you must have previously defined a global s1 to pass into the function.

Calling display does not modify the list you pass in, as written. Your code says “s1 is a name for whatever thing was passed in to the function; ok, now the first thing we’ll do is forget about that thing completely, and let s1 start referring instead to a newly created list. Now we’ll modify that list“. This has no effect on the value you passed in.

There is no reason to pass in a value here. (There is no real reason to create a function, either, but that’s beside the point.) You want to “create” something, so that is the output of your function. No information is required to create the thing you describe, so don’t pass any information in. To get information out, return it.

That would give you something like:

def display():
    s1 = list();
    for i in range(0, 9):
        s1[i] = i
    return s1

The next problem you will note is that your list will actually have only 9 elements, because the end point is skipped by the range function. (As side notes, [] works just as well as list(), the semicolon is unnecessary, s1 is a poor name for the variable, and only one parameter is needed for range if you’re starting from 0.) So then you end up with

def create_list():
    result = list()
    for i in range(10):
        result[i] = i
    return result

However, this is still missing the mark; range is not some magical keyword that’s part of the language the way for and def are, but instead it’s a function. And guess what that function returns? That’s right – a list of those integers. So the entire function collapses to

def create_list():
    return range(10)

and now you see why we don’t need to write a function ourselves at all; range is already the function we’re looking for. Although, again, there is no need or reason to “pre-size” the list.


回答 7

我感到惊讶的是,创建这些初始化列表的最简单方法不在这些答案中。只需在list函数中使用生成器:

list(range(9))

I’m a bit surprised that the easiest way to create an initialised list is not in any of these answers. Just use a generator in the list function:

list(range(9))

回答 8

n使用嵌套列表推导创建尺寸二维矩阵的一种简单方法:

m = [[None for _ in range(n)] for _ in range(n)]

One simple way to create a 2D matrix of size n using nested list comprehensions:

m = [[None for _ in range(n)] for _ in range(n)]

回答 9

这是我在python中的2D列表的代码,它将显示为no。输入的行数:

empty = []
row = int(input())

for i in range(row):
    temp = list(map(int, input().split()))
    empty.append(temp)

for i in empty:
    for j in i:
        print(j, end=' ')
    print('')

Here’s my code for 2D list in python which would read no. of rows from the input :

empty = []
row = int(input())

for i in range(row):
    temp = list(map(int, input().split()))
    empty.append(temp)

for i in empty:
    for j in i:
        print(j, end=' ')
    print('')

回答 10

我在寻找类似问题时遇到了这样的问题。我必须构建一个2D数组,然后用字典中的元素替换每个列表(在2D数组中)的某些元素。然后,我碰上了这个 SO问题,这帮助了我,也许这将帮助其他初学者得到解决。关键技巧是将2D数组初始化为numpy数组,然后使用array[i,j]代替array[i][j]

作为参考,这是我不得不使用的代码:

nd_array = []
for i in range(30):
    nd_array.append(np.zeros(shape = (32,1)))
new_array = []
for i in range(len(lines)):
    new_array.append(nd_array)
new_array = np.asarray(new_array)
for i in range(len(lines)):
    splits = lines[i].split(' ')
    for j in range(len(splits)):
        #print(new_array[i][j])
        new_array[i,j] = final_embeddings[dictionary[str(splits[j])]-1].reshape(32,1)

现在我知道我们可以使用列表理解了,但是为了简单起见,我使用了一个嵌套的for循环。希望这对遇到这篇文章的其他人有所帮助。

I came across this SO question while searching for a similar problem. I had to build a 2D array and then replace some elements of each list (in 2D array) with elements from a dict. I then came across this SO question which helped me, maybe this will help other beginners to get around. The key trick was to initialize the 2D array as an numpy array and then using array[i,j] instead of array[i][j].

For reference this is the piece of code where I had to use this :

nd_array = []
for i in range(30):
    nd_array.append(np.zeros(shape = (32,1)))
new_array = []
for i in range(len(lines)):
    new_array.append(nd_array)
new_array = np.asarray(new_array)
for i in range(len(lines)):
    splits = lines[i].split(' ')
    for j in range(len(splits)):
        #print(new_array[i][j])
        new_array[i,j] = final_embeddings[dictionary[str(splits[j])]-1].reshape(32,1)

Now I know we can use list comprehension but for simplicity sake I am using a nested for loop. Hope this helps others who come across this post.


回答 11

使它作为功能更可重用。

def createEmptyList(length,fill=None):
    '''
    return a (empty) list of a given length
    Example:
        print createEmptyList(3,-1)
        >> [-1, -1, -1]
        print createEmptyList(4)
        >> [None, None, None, None]
    '''
    return [fill] * length

Make it more reusable as a function.

def createEmptyList(length,fill=None):
    '''
    return a (empty) list of a given length
    Example:
        print createEmptyList(3,-1)
        >> [-1, -1, -1]
        print createEmptyList(4)
        >> [None, None, None, None]
    '''
    return [fill] * length

回答 12

s1 = []
for i in range(11):
   s1.append(i)

print s1

要创建列表,只需使用以下方括号:“ []”

要将某些内容添加到列表中,请使用list.append()

s1 = []
for i in range(11):
   s1.append(i)

print s1

To create a list, just use these brackets: “[]”

To add something to a list, use list.append()


回答 13

此代码生成一个包含10个随机数的数组。

import random
numrand=[]
for i in range(0,10):
   a = random.randint(1,50)
   numrand.append(a)
   print(a,i)
print(numrand)

This code generates an array that contains 10 random numbers.

import random
numrand=[]
for i in range(0,10):
   a = random.randint(1,50)
   numrand.append(a)
   print(a,i)
print(numrand)

简短的python列表之前的惯用语法是什么?

问题:简短的python列表之前的惯用语法是什么?

list.append()是添加到列表末尾的明显选择。这是有关失踪人员的合理解释list.prepend()。假设我的清单很短并且对性能的关注可以忽略不计,

list.insert(0, x)

要么

list[0:0] = [x]

惯用的?

list.append() is the obvious choice for adding to the end of a list. Here’s a reasonable explanation for the missing list.prepend(). Assuming my list is short and performance concerns are negligible, is

list.insert(0, x)

or

list[0:0] = [x]

idiomatic?


回答 0

s.insert(0, x)形式是最常见的。

但是,无论何时看到它,都可能是时候考虑使用collections.deque而不是列表了。

The s.insert(0, x) form is the most common.

Whenever you see it though, it may be time to consider using a collections.deque instead of a list.


回答 1

如果可以使用功能性方法,则以下内容很清楚

new_list = [x] + your_list

当然,你还没有插入xyour_list,而你已经创建了一个新的列表xpreprended它。

If you can go the functional way, the following is pretty clear

new_list = [x] + your_list

Of course you haven’t inserted x into your_list, rather you have created a new list with x preprended to it.


回答 2

简短的python列表之前的惯用语法是什么?

通常,您不想在Python中重复地放在列表之前。

如果它很,并且您没有做很多…那么就可以了。

list.insert

list.insert可以采用这种方式。

list.insert(0, x)

但这是无效的,因为在Python中,a list是一个指针数组,并且Python现在必须获取列表中的每个指针并将其向下移动一个,以将指向对象的指针插入第一个插槽中,因此,这实际上仅是有效的根据您的要求列出较短的清单。

这是实现该功能的CPython源代码的一个片段-如您所见,我们从数组的末尾开始,每次插入将所有内容向下移动一位:

for (i = n; --i >= where; )
    items[i+1] = items[i];

如果您希望容器/列表能够高效地添加元素,则需要一个链表。Python有一个双向链表,可以在开头和结尾快速插入-称为a deque

deque.appendleft

A collections.deque具有列表的许多方法。list.sort是一个exceptions,deque绝对不能完全用Liskov代替list

>>> set(dir(list)) - set(dir(deque))
{'sort'}

deque还有一个appendleft方法(以及popleft)。它deque是一个双端队列和一个双向链接的列表-不管长度如何,总是需要花费相同的时间来准备某些东西。在大O表示法中,列表的O(1)与O(n)时间。这是用法:

>>> import collections
>>> d = collections.deque('1234')
>>> d
deque(['1', '2', '3', '4'])
>>> d.appendleft('0')
>>> d
deque(['0', '1', '2', '3', '4'])

deque.extendleft

与此相关的还有双端队列的extendleft方法,该方法反复进行:

>>> from collections import deque
>>> d2 = deque('def')
>>> d2.extendleft('cba')
>>> d2
deque(['a', 'b', 'c', 'd', 'e', 'f'])

请注意,每个元素将一次添加一个,从而有效地颠倒了它们的顺序。

listvs的表现deque

首先,我们设置一些迭代的前缀:

import timeit
from collections import deque

def list_insert_0():
    l = []
    for i in range(20):
        l.insert(0, i)

def list_slice_insert():
    l = []
    for i in range(20):
        l[:0] = [i]      # semantically same as list.insert(0, i)

def list_add():
    l = []
    for i in range(20):
        l = [i] + l      # caveat: new list each time

def deque_appendleft():
    d = deque()
    for i in range(20):
        d.appendleft(i)  # semantically same as list.insert(0, i)

def deque_extendleft():
    d = deque()
    d.extendleft(range(20)) # semantically same as deque_appendleft above

和性能:

>>> min(timeit.repeat(list_insert_0))
2.8267281929729506
>>> min(timeit.repeat(list_slice_insert))
2.5210217320127413
>>> min(timeit.repeat(list_add))
2.0641671380144544
>>> min(timeit.repeat(deque_appendleft))
1.5863927800091915
>>> min(timeit.repeat(deque_extendleft))
0.5352169770048931

双端队列更快。随着列表的增加,我希望双端队列的性能更好。如果您可以使用双端队列,则extendleft可能会以这种方式获得最佳性能。

What’s the idiomatic syntax for prepending to a short python list?

You don’t usually want to repetitively prepend to a list in Python.

If it’s short, and you’re not doing it a lot… then ok.

list.insert

The list.insert can be used this way.

list.insert(0, x)

But this is inefficient, because in Python, a list is an array of pointers, and Python must now take every pointer in the list and move it down by one to insert the pointer to your object in the first slot, so this is really only efficient for rather short lists, as you ask.

Here’s a snippet from the CPython source where this is implemented – and as you can see, we start at the end of the array and move everything down by one for every insertion:

for (i = n; --i >= where; )
    items[i+1] = items[i];

If you want a container/list that’s efficient at prepending elements, you want a linked list. Python has a doubly linked list, which can insert at the beginning and end quickly – it’s called a deque.

deque.appendleft

A collections.deque has many of the methods of a list. list.sort is an exception, making deque definitively not entirely Liskov substitutable for list.

>>> set(dir(list)) - set(dir(deque))
{'sort'}

The deque also has an appendleft method (as well as popleft). The deque is a double-ended queue and a doubly-linked list – no matter the length, it always takes the same amount of time to preprend something. In big O notation, O(1) versus the O(n) time for lists. Here’s the usage:

>>> import collections
>>> d = collections.deque('1234')
>>> d
deque(['1', '2', '3', '4'])
>>> d.appendleft('0')
>>> d
deque(['0', '1', '2', '3', '4'])

deque.extendleft

Also relevant is the deque’s extendleft method, which iteratively prepends:

>>> from collections import deque
>>> d2 = deque('def')
>>> d2.extendleft('cba')
>>> d2
deque(['a', 'b', 'c', 'd', 'e', 'f'])

Note that each element will be prepended one at a time, thus effectively reversing their order.

Performance of list versus deque

First we setup with some iterative prepending:

import timeit
from collections import deque

def list_insert_0():
    l = []
    for i in range(20):
        l.insert(0, i)

def list_slice_insert():
    l = []
    for i in range(20):
        l[:0] = [i]      # semantically same as list.insert(0, i)

def list_add():
    l = []
    for i in range(20):
        l = [i] + l      # caveat: new list each time

def deque_appendleft():
    d = deque()
    for i in range(20):
        d.appendleft(i)  # semantically same as list.insert(0, i)

def deque_extendleft():
    d = deque()
    d.extendleft(range(20)) # semantically same as deque_appendleft above

and performance:

>>> min(timeit.repeat(list_insert_0))
2.8267281929729506
>>> min(timeit.repeat(list_slice_insert))
2.5210217320127413
>>> min(timeit.repeat(list_add))
2.0641671380144544
>>> min(timeit.repeat(deque_appendleft))
1.5863927800091915
>>> min(timeit.repeat(deque_extendleft))
0.5352169770048931

The deque is much faster. As the lists get longer, I would expect a deque to perform even better. If you can use deque’s extendleft you’ll probably get the best performance that way.


回答 3

如果有人像我一样发现这个问题,这是我对建议方法的性能测试:

Python 2.7.8

In [1]: %timeit ([1]*1000000).insert(0, 0)
100 loops, best of 3: 4.62 ms per loop

In [2]: %timeit ([1]*1000000)[0:0] = [0]
100 loops, best of 3: 4.55 ms per loop

In [3]: %timeit [0] + [1]*1000000
100 loops, best of 3: 8.04 ms per loop

如您所见,insert切片分配几乎是显式添加速度的两倍,并且结果非常接近。正如Raymond Hettinger指出的那样,这insert是更常见的选择,我个人更喜欢这种方式优先列出。

If someone finds this question like me, here are my performance tests of proposed methods:

Python 2.7.8

In [1]: %timeit ([1]*1000000).insert(0, 0)
100 loops, best of 3: 4.62 ms per loop

In [2]: %timeit ([1]*1000000)[0:0] = [0]
100 loops, best of 3: 4.55 ms per loop

In [3]: %timeit [0] + [1]*1000000
100 loops, best of 3: 8.04 ms per loop

As you can see, insert and slice assignment are as almost twice as fast than explicit adding and are very close in results. As Raymond Hettinger noted insert is more common option and I, personally prefer this way to prepend to list.


您如何从字符串列表中创建逗号分隔的字符串?

问题:您如何从字符串列表中创建逗号分隔的字符串?

您最好采用哪种方法来连接序列中的字符串,以便在每两个连续对之间添加一个逗号。也就是说,例如,您如何映射['a', 'b', 'c']'a,b,c'?(案例['s'][]应该分别映射到's'''。)

我通常最终会使用类似的东西''.join(map(lambda x: x+',',l))[:-1],但也会感到有些不满意。

What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance, ['a', 'b', 'c'] to 'a,b,c'? (The cases ['s'] and [] should be mapped to 's' and '', respectively.)

I usually end up using something like ''.join(map(lambda x: x+',',l))[:-1], but also feeling somewhat unsatisfied.


回答 0

my_list = ['a', 'b', 'c', 'd']
my_string = ','.join(my_list)
'a,b,c,d'

如果列表包含整数,则此方法无效


并且如果列表包含非字符串类型(例如整数,浮点数,布尔值,无),则请执行以下操作:

my_string = ','.join(map(str, my_list)) 
my_list = ['a', 'b', 'c', 'd']
my_string = ','.join(my_list)
'a,b,c,d'

This won’t work if the list contains integers


And if the list contains non-string types (such as integers, floats, bools, None) then do:

my_string = ','.join(map(str, my_list)) 

回答 1

为什么map/ lambda魔术?这不行吗?

>>> foo = ['a', 'b', 'c']
>>> print(','.join(foo))
a,b,c
>>> print(','.join([]))

>>> print(','.join(['a']))
a

如果列表中有数字,则可以使用列表理解:

>>> ','.join([str(x) for x in foo])

或生成器表达式:

>>> ','.join(str(x) for x in foo)

Why the map/lambda magic? Doesn’t this work?

>>> foo = ['a', 'b', 'c']
>>> print(','.join(foo))
a,b,c
>>> print(','.join([]))

>>> print(','.join(['a']))
a

In case if there are numbers in the list, you could use list comprehension:

>>> ','.join([str(x) for x in foo])

or a generator expression:

>>> ','.join(str(x) for x in foo)

回答 2

",".join(l)不适用于所有情况。我建议将CSV模块与StringIO一起使用

import StringIO
import csv

l = ['list','of','["""crazy"quotes"and\'',123,'other things']

line = StringIO.StringIO()
writer = csv.writer(line)
writer.writerow(l)
csvcontent = line.getvalue()
# 'list,of,"[""""""crazy""quotes""and\'",123,other things\r\n'

",".join(l) will not work for all cases. I’d suggest using the csv module with StringIO

import StringIO
import csv

l = ['list','of','["""crazy"quotes"and\'',123,'other things']

line = StringIO.StringIO()
writer = csv.writer(line)
writer.writerow(l)
csvcontent = line.getvalue()
# 'list,of,"[""""""crazy""quotes""and\'",123,other things\r\n'

回答 3

这是Python 3.0中允许非字符串列表项的替代解决方案:

>>> alist = ['a', 1, (2, 'b')]
  • 标准方式

    >>> ", ".join(map(str, alist))
    "a, 1, (2, 'b')"
  • 替代解决方案

    >>> import io
    >>> s = io.StringIO()
    >>> print(*alist, file=s, sep=', ', end='')
    >>> s.getvalue()
    "a, 1, (2, 'b')"

注意:逗号后的空格是故意的。

Here is a alternative solution in Python 3.0 which allows non-string list items:

>>> alist = ['a', 1, (2, 'b')]
  • a standard way

    >>> ", ".join(map(str, alist))
    "a, 1, (2, 'b')"
    
  • the alternative solution

    >>> import io
    >>> s = io.StringIO()
    >>> print(*alist, file=s, sep=', ', end='')
    >>> s.getvalue()
    "a, 1, (2, 'b')"
    

NOTE: The space after comma is intentional.


回答 4

你不只是想要:

",".join(l)

显然,如果您需要在值中引用/转义逗号等,它将变得更加复杂。在这种情况下,我建议您查看标准库中的csv模块:

https://docs.python.org/library/csv.html

Don’t you just want:

",".join(l)

Obviously it gets more complicated if you need to quote/escape commas etc in the values. In that case I would suggest looking at the csv module in the standard library:

https://docs.python.org/library/csv.html


回答 5

彼得·霍夫曼(Peter Hoffmann)

使用生成器表达式的好处是还可以生成迭代器,但可以节省导入itertools的时间。此外,列表推导通常首选映射,因此,我希望生成器表达式比imap首选。

>>> l = [1, "foo", 4 ,"bar"]
>>> ",".join(str(bit) for bit in l)
'1,foo,4,bar' 

@Peter Hoffmann

Using generator expressions has the benefit of also producing an iterator but saves importing itertools. Furthermore, list comprehensions are generally preferred to map, thus, I’d expect generator expressions to be preferred to imap.

>>> l = [1, "foo", 4 ,"bar"]
>>> ",".join(str(bit) for bit in l)
'1,foo,4,bar' 

回答 6

>>> my_list = ['A', '', '', 'D', 'E',]
>>> ",".join([str(i) for i in my_list if i])
'A,D,E'

my_list可以包含任何类型的变量。这样可以避免结果'A,,,D,E'

>>> my_list = ['A', '', '', 'D', 'E',]
>>> ",".join([str(i) for i in my_list if i])
'A,D,E'

my_list may contain any type of variables. This avoid the result 'A,,,D,E'.


回答 7

l=['a', 1, 'b', 2]

print str(l)[1:-1]

Output: "'a', 1, 'b', 2"
l=['a', 1, 'b', 2]

print str(l)[1:-1]

Output: "'a', 1, 'b', 2"

回答 8

使用列表推导的@ jmanning2k不利于创建新的临时列表。更好的解决方案是使用itertools.imap返回一个迭代器

from itertools import imap
l = [1, "foo", 4 ,"bar"]
",".join(imap(str, l))

@jmanning2k using a list comprehension has the downside of creating a new temporary list. The better solution would be using itertools.imap which returns an iterator

from itertools import imap
l = [1, "foo", 4 ,"bar"]
",".join(imap(str, l))

回答 9

这是清单的例子

>>> myList = [['Apple'],['Orange']]
>>> myList = ','.join(map(str, [i[0] for i in myList])) 
>>> print "Output:", myList
Output: Apple,Orange

更准确的:-

>>> myList = [['Apple'],['Orange']]
>>> myList = ','.join(map(str, [type(i) == list and i[0] for i in myList])) 
>>> print "Output:", myList
Output: Apple,Orange

示例2:

myList = ['Apple','Orange']
myList = ','.join(map(str, myList)) 
print "Output:", myList
Output: Apple,Orange

Here is an example with list

>>> myList = [['Apple'],['Orange']]
>>> myList = ','.join(map(str, [i[0] for i in myList])) 
>>> print "Output:", myList
Output: Apple,Orange

More Accurate:-

>>> myList = [['Apple'],['Orange']]
>>> myList = ','.join(map(str, [type(i) == list and i[0] for i in myList])) 
>>> print "Output:", myList
Output: Apple,Orange

Example 2:-

myList = ['Apple','Orange']
myList = ','.join(map(str, myList)) 
print "Output:", myList
Output: Apple,Orange

回答 10

我要说的csv是,库是这里唯一明智的选择,因为它是为应对所有csv用例(例如字符串中的逗号)而构建的。

要将列表输出l到.csv文件,请执行以下操作:

import csv
with open('some.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(l)  # this will output l as a single row.  

也可以用于writer.writerows(iterable)将多行输出到csv。

此示例与Python 3兼容,此处使用的另一个答案StringIO是Python 2。

I would say the csv library is the only sensible option here, as it was built to cope with all csv use cases such as commas in a string, etc.

To output a list l to a .csv file:

import csv
with open('some.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(l)  # this will output l as a single row.  

It is also possible to use writer.writerows(iterable) to output multiple rows to csv.

This example is compatible with Python 3, as the other answer here used StringIO which is Python 2.


回答 11

除非我缺少任何东西,否则','.join(foo)应该做您所要的。

>>> ','.join([''])
''
>>> ','.join(['s'])
's'
>>> ','.join(['a','b','c'])
'a,b,c'

(编辑:正如jmanning2k指出的那样,

','.join([str(x) for x in foo])

是更安全且相当Pythonic的,尽管如果元素可以包含逗号,则生成的字符串将很难解析-那时,您需要csv模块的全部功能,正如Douglas在他的回答中指出的那样。)

Unless I’m missing something, ','.join(foo) should do what you’re asking for.

>>> ','.join([''])
''
>>> ','.join(['s'])
's'
>>> ','.join(['a','b','c'])
'a,b,c'

(edit: and as jmanning2k points out,

','.join([str(x) for x in foo])

is safer and quite Pythonic, though the resulting string will be difficult to parse if the elements can contain commas — at that point, you need the full power of the csv module, as Douglas points out in his answer.)


回答 12

我的两分钱。我喜欢更简单的python单行代码:

>>> from itertools import imap, ifilter
>>> l = ['a', '', 'b', 1, None]
>>> ','.join(imap(str, ifilter(lambda x: x, l)))
a,b,1
>>> m = ['a', '', None]
>>> ','.join(imap(str, ifilter(lambda x: x, m)))
'a'

这是pythonic,适用于字符串,数字,无和空字符串。它很短并且满足要求。如果列表中不包含数字,则可以使用以下更简单的变体:

>>> ','.join(ifilter(lambda x: x, l))

同样,该解决方案不会创建新列表,而是使用迭代器,如@Peter Hoffmann指出的(谢谢)。

My two cents. I like simpler an one-line code in python:

>>> from itertools import imap, ifilter
>>> l = ['a', '', 'b', 1, None]
>>> ','.join(imap(str, ifilter(lambda x: x, l)))
a,b,1
>>> m = ['a', '', None]
>>> ','.join(imap(str, ifilter(lambda x: x, m)))
'a'

It’s pythonic, works for strings, numbers, None and empty string. It’s short and satisfies the requirements. If the list is not going to contain numbers, we can use this simpler variation:

>>> ','.join(ifilter(lambda x: x, l))

Also this solution doesn’t create a new list, but uses an iterator, like @Peter Hoffmann pointed (thanks).


获取map()以在Python 3.x中返回列表

问题:获取map()以在Python 3.x中返回列表

我正在尝试将列表映射为十六进制,然后在其他地方使用该列表。在python 2.6中,这很简单:

答: Python 2.6:

>>> map(chr, [66, 53, 0, 94])
['B', '5', '\x00', '^']

但是,在Python 3.1中,以上代码返回一个map对象。

B: Python 3.1:

>>> map(chr, [66, 53, 0, 94])
<map object at 0x00AF5570>

如何在Python 3.x上检索映射列表(如上面的A所示)?

另外,还有更好的方法吗?我的初始列表对象大约有45个项目,并且id喜欢将它们转换为十六进制。

I’m trying to map a list into hex, and then use the list elsewhere. In python 2.6, this was easy:

A: Python 2.6:

>>> map(chr, [66, 53, 0, 94])
['B', '5', '\x00', '^']

However, in Python 3.1, the above returns a map object.

B: Python 3.1:

>>> map(chr, [66, 53, 0, 94])
<map object at 0x00AF5570>

How do I retrieve the mapped list (as in A above) on Python 3.x?

Alternatively, is there a better way of doing this? My initial list object has around 45 items and id like to convert them to hex.


回答 0

做这个:

list(map(chr,[66,53,0,94]))

在Python 3+中,许多迭代可迭代对象的进程本身都会返回迭代器。在大多数情况下,这最终会节省内存,并且应该使处理速度更快。

如果您要做的只是最终遍历此列表,则无需将其转换为列表,因为您仍然可以map像这样遍历该对象:

# Prints "ABCD"
for ch in map(chr,[65,66,67,68]):
    print(ch)

Do this:

list(map(chr,[66,53,0,94]))

In Python 3+, many processes that iterate over iterables return iterators themselves. In most cases, this ends up saving memory, and should make things go faster.

If all you’re going to do is iterate over this list eventually, there’s no need to even convert it to a list, because you can still iterate over the map object like so:

# Prints "ABCD"
for ch in map(chr,[65,66,67,68]):
    print(ch)

回答 1

Python 3.5的新功能:

[*map(chr, [66, 53, 0, 94])]

多亏了其他拆包概述

更新

一直在寻找更短的途径,我发现这也行得通:

*map(chr, [66, 53, 0, 94]),

开箱也适用于元组。注意最后的逗号。这使其成为1个元素的元组。也就是说,它相当于(*map(chr, [66, 53, 0, 94]),)

它比带有方括号的版本短一个字符,但我认为最好写,因为您从星号-扩展语法开始,所以我觉得它比较软。:)

New and neat in Python 3.5:

[*map(chr, [66, 53, 0, 94])]

Thanks to Additional Unpacking Generalizations

UPDATE

Always seeking for shorter ways, I discovered this one also works:

*map(chr, [66, 53, 0, 94]),

Unpacking works in tuples too. Note the comma at the end. This makes it a tuple of 1 element. That is, it’s equivalent to (*map(chr, [66, 53, 0, 94]),)

It’s shorter by only one char from the version with the list-brackets, but, in my opinion, better to write, because you start right ahead with the asterisk – the expansion syntax, so I feel it’s softer on the mind. :)


回答 2

您为什么不这样做:

[chr(x) for x in [66,53,0,94]]

这称为列表理解。您可以在Google上找到很多信息,但是这里是list comprehensions上的Python(2.6)文档的链接。不过,您可能对Python 3文档更感兴趣。

Why aren’t you doing this:

[chr(x) for x in [66,53,0,94]]

It’s called a list comprehension. You can find plenty of information on Google, but here’s the link to the Python (2.6) documentation on list comprehensions. You might be more interested in the Python 3 documenation, though.


回答 3

返回列表的地图功能具有保存键入的优点,尤其是在交互式会话期间。您可以定义返回列表的lmap函数(类似于python2的函数imap):

lmap = lambda func, *iterable: list(map(func, *iterable))

然后打电话 lmap而不是即可map完成工作:比 lmap(str, x)短5个字符(在这种情况下为30%),list(map(str, x))并且肯定比短[str(v) for v in x]。您也可以创建类似的功能filter

对原始问题有一条评论:

我建议重命名为Geting map()以返回Python 3. *中的列表,因为它适用于所有Python3版本。有没有办法做到这一点?– meawoppl 1月24日17:58

有可能做到这一点,但它是一个非常糟糕的主意。只是为了好玩,您可以(但不应)执行以下操作:

__global_map = map #keep reference to the original map
lmap = lambda func, *iterable: list(__global_map(func, *iterable)) # using "map" here will cause infinite recursion
map = lmap
x = [1, 2, 3]
map(str, x) #test
map = __global_map #restore the original map and don't do that again
map(str, x) #iterator

List-returning map function has the advantage of saving typing, especially during interactive sessions. You can define lmap function (on the analogy of python2’s imap) that returns list:

lmap = lambda func, *iterable: list(map(func, *iterable))

Then calling lmap instead of map will do the job: lmap(str, x) is shorter by 5 characters (30% in this case) than list(map(str, x)) and is certainly shorter than [str(v) for v in x]. You may create similar functions for filter too.

There was a comment to the original question:

I would suggest a rename to Getting map() to return a list in Python 3.* as it applies to all Python3 versions. Is there a way to do this? – meawoppl Jan 24 at 17:58

It is possible to do that, but it is a very bad idea. Just for fun, here’s how you may (but should not) do it:

__global_map = map #keep reference to the original map
lmap = lambda func, *iterable: list(__global_map(func, *iterable)) # using "map" here will cause infinite recursion
map = lmap
x = [1, 2, 3]
map(str, x) #test
map = __global_map #restore the original map and don't do that again
map(str, x) #iterator

回答 4

我的旧注释转换为更好的可见性:为了更好地“更好地做到这一点” map,如果您的输入已知为ASCII序数,则通常可以更快地转换为bytesla bytes(list_of_ordinals).decode('ascii')。这样就可以得到一个str值,但是如果您需要a list来实现可变性或类似功能,则可以将其转换(并且转换速度仍然更快)。例如,在微ipython基准中转换45个输入:

>>> %%timeit -r5 ordinals = list(range(45))
... list(map(chr, ordinals))
...
3.91 µs ± 60.2 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... [*map(chr, ordinals)]
...
3.84 µs ± 219 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... [*bytes(ordinals).decode('ascii')]
...
1.43 µs ± 49.7 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... bytes(ordinals).decode('ascii')
...
781 ns ± 15.9 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each)

如果您将其保留为str,则最快的map解决方案会花费大约20%的时间;即使转换回列表,它仍然不到最快map解决方案的40%。批量转换通过bytesbytes.decode然后批量转换回以list节省大量工作,但是如上所述,仅当您所有的输入都是ASCII序号(或每个字符特定于区域设置编码的字节中的序号latin-1)时,该方法才有效。

Converting my old comment for better visibility: For a “better way to do this” without map entirely, if your inputs are known to be ASCII ordinals, it’s generally much faster to convert to bytes and decode, a la bytes(list_of_ordinals).decode('ascii'). That gets you a str of the values, but if you need a list for mutability or the like, you can just convert it (and it’s still faster). For example, in ipython microbenchmarks converting 45 inputs:

>>> %%timeit -r5 ordinals = list(range(45))
... list(map(chr, ordinals))
...
3.91 µs ± 60.2 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... [*map(chr, ordinals)]
...
3.84 µs ± 219 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... [*bytes(ordinals).decode('ascii')]
...
1.43 µs ± 49.7 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... bytes(ordinals).decode('ascii')
...
781 ns ± 15.9 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each)

If you leave it as a str, it takes ~20% of the time of the fastest map solutions; even converting back to list it’s still less than 40% of the fastest map solution. Bulk convert via bytes and bytes.decode then bulk converting back to list saves a lot of work, but as noted, only works if all your inputs are ASCII ordinals (or ordinals in some one byte per character locale specific encoding, e.g. latin-1).


回答 5

list(map(chr, [66, 53, 0, 94]))

map(func,* iterables)->地图对象创建一个迭代器,该迭代器使用每个可迭代对象的参数来计算函数。当最短的迭代次数用尽时停止。

“进行迭代”

表示它将返回迭代器。

“使用每个可迭代对象的参数来计算函数”

意味着迭代器的next()函数将为每个可迭代对象取一个值,并将每个值传递给该函数的一个位置参数。

因此,您可以从map()函数中获得一个迭代器,然后jsut将其传递给内置函数list()或使用列表推导。

list(map(chr, [66, 53, 0, 94]))

map(func, *iterables) –> map object Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted.

“Make an iterator”

means it will return an iterator.

“that computes the function using arguments from each of the iterables”

means that the next() function of the iterator will take one value of each iterables and pass each of them to one positional parameter of the function.

So you get an iterator from the map() funtion and jsut pass it to the list() builtin function or use list comprehensions.


回答 6

除了上述答案外Python 3,我们还可以简单地listmapas中创建结果值a

li = []
for x in map(chr,[66,53,0,94]):
    li.append(x)

print (li)
>>>['B', '5', '\x00', '^']

我们可以通过另一个例子来概括我被打动的情况,对地图的操作也可以像regex问题中一样的方式处理,我们可以编写函数以获取list要映射的项目并同时获取结果集。例如

b = 'Strings: 1,072, Another String: 474 '
li = []
for x in map(int,map(int, re.findall('\d+', b))):
    li.append(x)

print (li)
>>>[1, 72, 474]

In addition to above answers in Python 3, we may simply create a list of result values from a map as

li = []
for x in map(chr,[66,53,0,94]):
    li.append(x)

print (li)
>>>['B', '5', '\x00', '^']

We may generalize by another example where I was struck, operations on map can also be handled in similar fashion like in regex problem, we can write function to obtain list of items to map and get result set at the same time. Ex.

b = 'Strings: 1,072, Another String: 474 '
li = []
for x in map(int,map(int, re.findall('\d+', b))):
    li.append(x)

print (li)
>>>[1, 72, 474]

回答 7

您可以尝试通过仅迭代对象中的每个项目并将其存储在另一个变量中来从地图对象获取列表。

a = map(chr, [66, 53, 0, 94])
b = [item for item in a]
print(b)
>>>['B', '5', '\x00', '^']

You can try getting a list from the map object by just iterating each item in the object and store it in a different variable.

a = map(chr, [66, 53, 0, 94])
b = [item for item in a]
print(b)
>>>['B', '5', '\x00', '^']

回答 8

使用python中的列表理解和基本的地图函数实用程序,还可以做到这一点:

chi = [x for x in map(chr,[66,53,0,94])]

Using list comprehension in python and basic map function utility, one can do this also:

chi = [x for x in map(chr,[66,53,0,94])]