[英]Comparing elements of a list with those of sublists python
我正在嘗試編寫一個將從列表中獲取值的函數,然后查看它是否在子列表中的兩個值的范圍內。 希望我的代碼能更好地解釋它:
list1 = [1, 2, 3, 4, 5]
list2 = [[1, 3], [2, 4]]
answer = []
c = 0
for elem in list1:
if list2[c] <= int(elem) <= list2[c+1]:
answer.append(elem)
sys.stdout.write(str(answer) + ' ')
c += 1
Expected Output:
1 2 3
2 3 4
因此,我想做的是查看list1中元素的值是否在list2中每個子列表的范圍內,當然,這些值會添加到列表中,然后打印出來。 我收到錯誤消息:
Traceback (most recent call last):
File "Task11.py", line 54, in <module>
main()
File "Task11.py", line 51, in main
input_string()
File "Task11.py", line 48, in input_string
list_interval(input_list, query_values)
File "Task11.py", line 16, in list_interval
if int(list2[c]) <= int(elem) <= int(list2[c+1]):
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
我不了解,但是我不確定如何以我提到的方式實際使用子列表。
使用list-comprehension在list2
指定的范圍參數中查找list1
中的所有元素:
list1 = [1, 2, 3, 4, 5]
list2 = [[1, 3], [2, 4]]
lst = [[c for c in list1 if c in range(x, y+1)] for x, y in list2]
print(lst)
# [[1, 2, 3], [2, 3, 4]]
range()
有助於創建一個從其第一個參數開始(不包括最后一個參數)的數字范圍。 它還帶有一個可選的step參數,您可以在其中指定結果輸出中相鄰數字之間的差。 如果為空則表示步驟為1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.