我有一个项目列表,我需要使用特定的“键”将项目分开。假设我需要所有跟在“ X”后面的项目->列表可能看起来像这样:Y1 1-2 X1 3-5 Z1 6-8, Y2 3-5 X2 5-7 Z2 5-9
,所以我需要获取X个“ 3-5
”和“ 5-7
”的“值”。这些应该以以下方式返回:3 4 5
和5 6 7
并以它们自己的行返回,以便可以在其他函数中使用它们。
我也尝试过将“ X”带到自己的字典中,但是问题仍然相同。我也知道end =“”,但这并不能帮助我。
def get_x_values(list_parameter):
list_of_items = []
list_of_x = []
for i in list_parameter:
i = i.split(' ')
for item in i:
if item != '':
list_of_items.append(item)
for item, next_item in zip(list_of_items, list_of_items[1:]):
if item == 'X':
list_of_x.append(next_item)
for x in list_of_x:
for i in range(int(x[0]), int(x[-1]) + 1):
yield i
当我循环屈服值谷时,我得到的X值是这样的:
3
4
5
5
6
7
当我这样需要它们时:
3 4 5
5 6 7
任何帮助表示赞赏。
答案 0 :(得分:1)
我修改了您的代码,使其可以正常工作。
def get_x_values(list_parameter):
list_of_items = []
for i in list_parameter:
i = i.split(' ')
for item in i:
if item != '':
list_of_items.append(item)
for item, next_item in zip(list_of_items, list_of_items[1:]):
if item == 'X':
range_list = list(range(int(next_item[0]), int(next_item[-1]) + 1))
yield " ".join(str(number) for number in range_list)
lst = ["Y 1-2 X 3-5 Z 6-8", "Y 3-5 X 5-7 Z 5-9"]
result = get_x_values(lst)
for x in result:
print(x)
但是,这不是最优雅的解决方案。但是我想这对您来说更容易理解,因为它非常接近您自己的尝试。
我希望它能对您有所帮助。让我知道是否还有任何疑问。祝你有美好的一天!
答案 1 :(得分:0)
您需要
例如:
# there is a pesky , in your string, we strip it out
inp = "Y1 1-2 X1 3-5 Z1 6-8, Y2 3-5 X2 5-7 Z2 5-9"
formatted_input = [a.rstrip(",") for a in inp.split(" ")]
print(formatted_input)
# put keys and values together and convert values to int-list
as_dict = {formatted_input[a]:list(map(int,formatted_input[a+1].split("-")))
for a in range(0,len(formatted_input),2)}
print(as_dict)
# create correct ranges from int-list
as_dict_ranges = {key:list(range(a,b+1)) for key,(a,b) in as_dict.items()}
print(as_dict_ranges)
# you could put all the above in a function and yield the dict-items from here:
# yield from as_dict_ranges.item()
# and filter them for key = X.... outside
# filter for keys that start with X
for k,v in as_dict_ranges.items():
if k.startswith("X"):
print(*v, sep=" ") # decompose the values and print seperated onto one line
输出:
# formatted_input
['Y1', '1-2', 'X1', '3-5', 'Z1', '6-8', 'Y2', '3-5', 'X2', '5-7', 'Z2', '5-9']
# as_dict
{'Y1': [1, 2], 'X1': [3, 5], 'Z1': [6, 8],
'Y2': [3, 5], 'X2': [5, 7], 'Z2': [5, 9]}
# as_dict_ranges
{'Y1': [1, 2], 'X1': [3, 4, 5], 'Z1': [6, 7, 8],
'Y2': [3, 4, 5], 'X2': [5, 6, 7], 'Z2': [5, 6, 7, 8, 9]}
# output for keys X...
3 4 5
5 6 7
如果不想打印map(int,...)值,则可以省略一个列表转换:
as_dict = {formatted_input[a]:map(int,formatted_input[a+1].split("-"))
for a in range(0,len(formatted_input),2)}
文档: