【问题标题】:Pick a specific element from a list and append it on to another list从列表中选择特定元素并将其附加到另一个列表
【发布时间】:2017-04-12 19:58:21
【问题描述】:

我有两个列表 x 和 y

x = ['13', '77', '58', '792', '171']

y = []

我需要将 x 中以“7”开头的所有元素添加到 y

我已经尝试过类似的方法:

i = 0
for i in range(len(x)):
    if i[0] == '7':
        y.append(i[0])
        i += 1

【问题讨论】:

  • y.extend(e for e in x if e.startswith('7'))
  • y.append(i[0])更改为y.append(i)
  • i += 1 不会对您的程序产生影响,您也不需要在循环之前添加i = 0

标签: python list loops append


【解决方案1】:
In [16]: x = ['13', '77', '58', '792', '171']

In [17]: y = [i for i in x if i.startswith('7')]

In [18]: y
Out[18]: ['77', '792']

【讨论】:

    【解决方案2】:

    我选择了一个更详细的解决方案,它是正确的并且应该易于阅读。

    x = ['13', '77', '58', '792', '171']
    
    y = []
    
    for e in x:
        if e[0] == '7':
            y.append(e)
    

    【讨论】:

    • 如何删除我拥有的字符串列表中的第一个字符:x = ['76776', '766', '71'] 我正在尝试返回 x = ['6776', '66', '1']
    • @dontworry123 试试这个y.append(e[1:]) 代替y.append(e)
    【解决方案3】:

    另一种简洁的方法是使用方便的 filter() 函数,该函数接受一个返回“bool”的函数(在本例中为 lambda 函数。)

    x = ['13', '77', '58', '792', '171']
    y = list(filter(lambda item: item.startswith('7'), x))
    

    (这不会将元素附加到 y,不确定是否需要。) 不是防弹的,但适用于您的示例。

    【讨论】:

      猜你喜欢
      • 2020-10-29
      • 1970-01-01
      • 2016-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      • 2015-11-26
      • 1970-01-01
      相关资源
      最近更新 更多