不满足某些条件时从列表中删除元组

时间:2019-11-26 15:43:35

标签: python tuples

我有一个元组列表,并且如果元组中的第一个元素中没有数字,我想删除一个元组。下面是我目前拥有的代码。

x = [('akj_vx', 1.2559392760527808, 1.0), ('39Sbw£', 1.5930205922, 2.0), ('bg1HEw*', 1.95830294, 1.0)]

for item in x:
  print("Time", item[1],": ID", item[0], "Exponent", item[2],)
  if re.search(r"\d", item[0]):
    print("Task", item[0] ,"Accepted \n")
  else:
    print("Task", item[0], "discarded \n")

print(x)

当我打印列表(x)时,我希望输出为:

[('39Sbw£', 1.5930205922, 2.0), ('bg1HEw*', 1.95830294, 1.0)]

我可以在代码中添加些什么来确保这一点?

3 个答案:

答案 0 :(得分:1)

您可以使用列表推导来创建满足条件的列表,而不是删除不必要的项目:

if (groceries.get(i) instanceof Food) {
   Food.saveToFile((Food)groceries.get(i));
}
else
   Beverage.saveToFile((Beverage)groceries.get(i));

或者,您也可以使用纯Python(没有任何模块依赖性):

x = [item for item in x if re.search(r"\d", item[0])]

根据评论中的要求,您还可以按索引删除(不推荐):

x = [item for item in x if any(y.isdigit() for y in item[0])]

答案 1 :(得分:0)

您可以使用一些列表理解:custom_source= new rtc::RefCountedObject<CustomVideoSource>(); // create video track from our custom source rtc::scoped_refptr<webrtc::VideoTrackInterface> custom_video_track( g_peer_connection_factory->CreateVideoTrack( kVideoLabel, custom_source)); //add to stream stream->AddTrack(custom_video_track);

答案 2 :(得分:0)

如果您不想使用re模块,可以使用此模块:

x = [('akj_vx', 1.2559392760527808, 1.0), ('39Sbw£', 1.5930205922, 2.0), ('bg1HEw*', 1.95830294, 1.0)]

x = [i for i in x if any(ch in '0123456789' for ch in i[0])]
print(x)

打印:

[('39Sbw£', 1.5930205922, 2.0), ('bg1HEw*', 1.95830294, 1.0)]

编辑(或使用.isdigit()):

x = [i for i in x if any(ch.isdigit() for ch in i[0])]
相关问题