简体   繁体   English

如何在python中将一个元素从列表移动到另一个

[英]how to move one element from a list to another in python

def ListNum(x):
    list1 = []
    for i in (x):
        if x[i] < x [i + 1]:
            list1.append[i]
        else:
            break
    return(list1)
ListNum([1,2,3,4,5,6,2,3,4])

So, I input a list of numbers and go through the list and check if the first value in that list is less than the second value if so add it to list1 , carry on until the value is greater than the next value. 因此,我输入了一个数字列表,然后遍历该列表,并检查该列表中的第一个值是否小于第二个值(如果是的话)将其添加到list1 ,继续操作直到该值大于下一个值。

So, if I input ListNum([1,2,3,4,5,6,2,3,4]) 因此,如果我输入ListNum([1,2,3,4,5,6,2,3,4])

i should get list1[1,2,3,4,5,6] 我应该得到list1[1,2,3,4,5,6]

but its not working 但它不起作用

You don't need the indexes, you can zip your list like this: 您不需要索引,可以像这样压缩列表:

def ListNum(x):
    list1 = []
    for e1, e2 in zip(x, x[1:]):
        if e1 < e2:
            list1.append(e1)
        else:
            break
    return list1

This also has the benefit of fixing the bug when the list is sorted. 这还具有在对列表进行排序时修复错误的好处。

If you do for i in x , you iterate through elements in x , not their indexes. 如果for i in x ,则要遍历x元素,而不是它们的索引。

To iterate through indexes, you have to do for i in range(len(x)) . 要遍历索引,必须for i in range(len(x))进行操作。

I assume that you never want to add the last item in x to list1 because there isn't an item after it to compare it with. 我假设您永远都不想将x的最后一项添加到list1因为它后面没有要与之比较的项目。

Your code doesn't work properly because for i in (x): iterates over the items in x , not their indices. 您的代码无法正常工作,因为for i in (x):遍历x项目 ,而不是其索引。 But even if it did iterate over the indices your code could crash with an IndexError because it could attempt to compare the last item in the list with the item after it, which doesn't exist 但是,即使它确实遍历了索引,您的代码也可能因IndexError崩溃,因为它可能会尝试将列表中的最后一项与其后的一项进行比较(不存在)

Here are several ways to do this. 这里有几种方法可以做到这一点。

from itertools import takewhile

def list_nums0(x):
    list1 = []
    for i in range(len(x) - 1):
        if x[i] < x[i + 1]:
            list1.append(x[i])
        else:
            break
    return list1

def list_nums1(x):
    list1 = []
    for u, v in zip(x, x[1:]):
        if u < v:
            list1.append(u)
        else:
            break
    return list1

def list_nums2(x):
    list1 = []
    for i, u in enumerate(x[:-1], 1):
        if u < x[i]:
            list1.append(u)
        else:
            break
    return list1

def list_nums3(x):
    return [t[0] for t in takewhile((lambda a:a[0] < a[1]), zip(x, x[1:]))]

list_nums = list_nums3
print(list_nums([1,2,3,4,5,6,2,3,4]))

output 输出

[1, 2, 3, 4, 5]

list_nums0 simply iterates over the indices of x . list_nums0只是迭代x的索引。

list_nums1 uses zip to iterate in parallel over x and x[1:] . list_nums1使用zipxx[1:]并行迭代。 This puts the current & next items into u and v . 这会将当前和下一个项目放入uv

list_nums2 uses enumerate to get the current item in u and the index of the next item in i . list_nums2使用enumerate获取u的当前项目以及i下一项的索引。

list_nums3 uses takewhile to iterate over the tuples yielded by zip until we get a pair of items that don't satisfy the test. list_nums3使用takewhile来遍历zip产生的元组,直到获得一对不满足测试的项目。 It performs the whole operation in a list comprehension, which is slightly more efficient that using .append in a traditional for loop. 它以列表理解的方式执行整个操作,这比在传统的for循环中使用.append效率更高。


Here are versions that also add the last item in the list if we get that far. 如果到此为止,这些版本也会在列表中添加最后一项。 The simple way to do this is to create a new temporary list that has a last item guaranteed to be greater than the "real" last item. 执行此操作的简单方法是创建一个新的临时列表,该列表的最后一项保证大于“实际”最后一项。

from itertools import takewhile

def list_nums0(x):
    x = x + [x[-1] + 1]
    list1 = []
    for i in range(len(x) - 1):
        if x[i] < x[i + 1]:
            list1.append(x[i])
        else:
            break
    return list1

def list_nums1(x):
    list1 = []
    for u, v in zip(x, x[1:] + [x[-1] + 1]):
        if u < v:
            list1.append(u)
        else:
            break
    return list1

def list_nums2(x):
    x = x + [x[-1] + 1]
    list1 = []
    for i, u in enumerate(x[:-1], 1):
        if u < x[i]:
            list1.append(u)
        else:
            break
    return list1

def list_nums3(x):
    return [t[0] for t in takewhile((lambda a:a[0] < a[1]), zip(x, x[1:] + [x[-1] + 1]))]

# test all the functions

funcs = (
    list_nums0,
    list_nums1,
    list_nums2,
    list_nums3,
)

data = [1, 2, 3, 4, 5, 6, 0]
print('data', data)
for i, list_nums in enumerate(funcs):
    print(i, list_nums(data))

data = [1, 2, 3, 4, 5, 6]
print('data', data)
for i, list_nums in enumerate(funcs):
    print(i, list_nums(data))

output 输出

data [1, 2, 3, 4, 5, 6, 0]
0 [1, 2, 3, 4, 5]
1 [1, 2, 3, 4, 5]
2 [1, 2, 3, 4, 5]
3 [1, 2, 3, 4, 5]
data [1, 2, 3, 4, 5, 6]
0 [1, 2, 3, 4, 5, 6]
1 [1, 2, 3, 4, 5, 6]
2 [1, 2, 3, 4, 5, 6]
3 [1, 2, 3, 4, 5, 6]

Of course, this strategy will fail if you pass an empty list. 当然,如果您传递一个空列表,此策略将失败。 The simple way around that is to put this at the top of the function: 解决这个问题的简单方法是将其放在函数顶部:

if not x:
    return []

Eg, 例如,

def list_nums1(x):
    if not x:
        return []
    list1 = []
    for u, v in zip(x, x[1:] + [x[-1] + 1]):
        if u < v:
            list1.append(u)
        else:
            break
    return list1

We can rewrite list_nums3 like this to keep it a one-liner: 我们可以像这样重写list_nums3使其保持一线状态:

def list_nums3(x):
    return [] if not x else [t[0] for t in takewhile((lambda a:a[0] < a[1]), zip(x, x[1:] + [x[-1] + 1]))]

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

相关问题 如何在python中将项目从一个列表移动到另一个列表? - How to move Items from one list to the another list in python? 如果一个列表中的元素存在于 Python 中的另一个列表中,如何打印该元素? - How to print an element from one list if it exists in another list in Python? 如何将一个项目从一个列表移动到另一个列表 - How to move an item from one list into another 如何将Python列表中的元素移动到列表中的其他位置(而不是末尾) - How to move an element in a Python list to another position in the list (not the end) 在python中将元素从一个列表复制到另一个 - Copying element from one list to another in python Python 从一个元素到另一个元素的块列表 - Python chunk list from one element to another 如何在Python中将多个项目从一个列表移到另一个 - How can i move more than one item from one list to another in Python 在Python的另一个列表中从一个列表中查找元素 - finding an element from one list in another list in python 如何将文件从一个文件夹从python移动到另一个文件夹 - How to move Files from one folder to another folder from python 如何使用 python 将数据从一个源移动到另一个源? - how to move data from one source to another source with python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM