1

特定の範囲 (0 ~ 100 とします) 内の乱数のリストを生成するコードが少しありますが、範囲 (45 ~ 55) 内に表示される数字は表示されないようにしたいと考えています。

私の特定の目的のために、その範囲に表示される数字に 11 を加算/減算する方法を知りたいです。私は次の行を書きました:

desired_list = [integer_list[i] - 11 for i in range(len(integer_list)) if integer_list[i] in list_of_consecutive_unwanted_integers]

しかし、今、desired_list を印刷すると、乱数を取得する約 4/5 回、空の括弧が表示されます。この奇妙な現象を説明する必要はありません。ありがとう。

4

3 に答える 3

1
integer_list[i] in list_of_consecutive_unwanted_integers

整数が不要かどうかをチェックし、「不要なリスト」にないものを破棄し、不要なものを保持します。

この問題を解決する方法は次のとおりです。

>>> # let's get 20 random integers in [0, 100]
>>> random_integers = (randint(0, 100) for _ in xrange(20))
>>> [x - 11 if 45 <= x <= 55 else x for x in random_integers]
[62, 0, 28, 34, 36, 96, 20, 19, 84, 17, 85, 83, 17, 91, 98, 33, 5, 100, 94, 97]

x - 11 if 45 <= x <= 55 else x整数が [45, 55] の範囲にある場合に 11 を減算する条件式です。これを次のように書くこともできます

x - 11 * (45 <= x <= 55)

と には数値 1 と 0 があるためTrueですFalse

于 2013-01-30T21:50:31.947 に答える
0
    >>> l = range(100)
    >>>[アイテム<45またはアイテム>55の場合、lのアイテムのアイテム]
    [0、1、2、3、4、5、6、7、8、9、10、11、12、13、14、15、16、17、18、19、20、21、22、23、24 、25、26、27、28、29、30、31、32、33、34、35、36、37、38、39、40、41、42、43、44、56、57、58、59、60 、61、62、63、64、65、66、67、68、69、70、71、72、73、74、75、76、77、78、79、80、81、82、83、84、85 、86、87、88、89、90、91、92、93、94、95、96、97、98、99]

于 2013-01-30T22:36:48.357 に答える
0
>>> l    # Let l be the list of numbers in the range(0, 100) with some elements
[3, 4, 5, 45, 48, 6, 55, 56, 60]
>>> filter(lambda x: x < 45 or x > 55, l) # Remove elements in the range [45, 55]
[3, 4, 5, 6, 56, 60]

filter関数fを入力シーケンスに適用し、 f(item) が返すシーケンスの項目を返しますTrue

filter(...)
filter(関数またはなし、シーケンス) -> リスト、タプル、または文字列

Return those items of sequence for which function(item) is true. If
function is None, return the items that are true.  If sequence is a tuple
or string, return the same type, else return a list.
于 2013-01-30T22:27:46.723 に答える