使用Python 2.7。我在列表中有以下列表:
channels = [[ch1a.twist, ch1b.twist, ch1c.twist, ch2a.bop, ch2b.bop, ch3c.pull]]
new_list = []
我想将以下逻辑应用于我的代码:
我想运行for循环,以便
channels = [...]
new_list = []
for "blah":
do stuff
print new_list
>> new_list = [ch1a.twist, ch2a.bop, ch3c.pull]
到目前为止我已经
了 for list in channels:
for ch in list:
try:
prefix, suffix = ch.split('.')
except ValueError:
pass
else:
if 'a' in prefix:
new_list.append(ch)
elif 'b' in prefix:
new_list.append(ch)
但是这仍然是ch1a.twist和ch1b.twist ... grrrrrr。我认为'elif'应该模仿以下逻辑:'如果以前的条件没有达到,那么执行以下'
答案 0 :(得分:1)
假设:
ch1a.twist
等人成为字符串文字,只是忘记了引号channels
只包含一个列表然后,您可以使用groupby
按频道名称对项目进行分组,并使用next
提取每个频道的第一个匹配项。
import itertools
def channel_name(channel):
prefix, suffix = channel.split(".")
return prefix[:-1]
channels = [["ch1a.twist", "ch1b.twist", "ch1c.twist", "ch2a.bop", "ch2b.bop", "ch3c.pull"]]
result = [next(v) for k,v in itertools.groupby(channels[0], key=channel_name)]
print(result)
结果:
['ch1a.twist', 'ch2a.bop', 'ch3c.pull']
答案 1 :(得分:0)
我得到了与@roganjosh相同的错误,所以我假设你的列表中的列表应该包含字符串(如果它们不是,那么它就变得很简单了。)< / p>
您提供的代码的主要问题是,如果您点击代码检查是否&#39;&#39;在前缀中,您永远不会想知道您是否已将频道编号添加到new_list
。
我发现修改代码的最简单方法如下(它不是很漂亮,但我试图让代码尽可能不被触摸):
首先,使用channels[0].sort()
接下来,通过使用channelNumbers = []
接下来,我拆分前缀,以便将频道编号与频道版本分开:
channelNumber = prefix[:-1]
channelVersion = prefix[-1:]
最后,我调整了您的elif
语句,以便只有在未添加频道号时才会添加b或c版本:
elif 'b' in prefix and not channelNumber in channelNumbers:
和elif 'c' in prefix and not channelNumber in channelNumbers:
所以完整的代码变为:
channels = [['ch1a.twist', 'ch1b.twist', 'ch1c.twist', 'ch2a.bop', 'ch2b.bop', 'ch3c.pull']]
new_list = []
channelNumbers = []
channels[0].sort()
for list in channels:
for ch in list:
try:
prefix, suffix = ch.split('.')
channelNumber = prefix[:-1]
channelVersion = prefix[-1:]
except ValueError:
pass
else:
if channelVersion == 'a':
new_list.append(ch)
channelNumbers.append(channelNumber)
elif channelVersion == 'b' and not channelNumber in channelNumbers:
new_list.append(ch)
elif channelVersion == 'c' and not channelNumber in channelNumbers:
new_list.append(ch)
print(new_list)
根据您的要求输出:['ch1a.twist', 'ch2a.bop', 'ch3c.pull']